Toast之完全自定義——媽媽再也不用擔心Toast太醜了

一,最終的效果

在這裏插入圖片描述

二,代碼實現

1,主活動

/**
 * @author zhangyan 
 * @data 2019/3/6
 */
public class MainActivity extends AppCompatActivity {

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button toast = findViewById(R.id.toast);

        toast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              //  Toast.makeText(MainActivity.this, "老了.老弟", Toast.LENGTH_SHORT).show();
                midToast("來了,老弟", 3);
            }
        });


    }
   
   /**
   *自定義Toast
   **/
    private void midToast(String str, int showTime)
    {
        LayoutInflater inflater = getLayoutInflater();
        //加載佈局
        View view = inflater.inflate(R.layout.main_layout, (ViewGroup) findViewById(R.id.lly_toast));
        ImageView img_logo = view.findViewById(R.id.img_logo);
        TextView tv_msg = view.findViewById(R.id.tv_msg);
        tv_msg.setText(str);
        Toast toast = new Toast(MainActivity.this);
        //顯示位置
        toast.setGravity(Gravity.CENTER, 0, 0);
        //設置時長
        toast.setDuration(Toast.LENGTH_LONG);
        //設置視圖
        toast.setView(view);
        toast.show();
    }

2,佈局文件main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lly_toast"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_toast"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img_logo"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:src="@mipmap/meizi" />

    <TextView
        android:id="@+id/tv_msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:textSize="20sp" />

</LinearLayout>

3,Toast背景樣式bg_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 設置透明背景色 -->
    <solid android:color="#BADB66" />
    <!-- 設置一個黑色邊框 -->
    <stroke
        android:width="1px"
        android:color="#FFFFFF" />
    <!-- 設置四個圓角的半徑 -->
    <corners
        android:bottomLeftRadius="50px"
        android:bottomRightRadius="50px"
        android:topLeftRadius="50px"
        android:topRightRadius="50px" />
    <!-- 設置一下邊距,讓空間大一點 -->
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
</shape>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章