【Android-自定義控件】 漂亮的Toast

修改Toast屬性,美化Toast

//建立一個Toast
Toast toast=new Toast(getApplicationContext());

//建立Toast中的文字
TextView textView=new TextView(getApplicationContext());
textView.setText("可愛的喵喵");
//文字設置顏色
textView.setTextColor(Color.WHITE);
//文字設置大小
textView.setTextSize(20);

//建立Toast中的圖片
ImageView imageView=new ImageView(getApplicationContext());
imageView.setImageResource(R.mipmap.ic_launcher);

//組合文本加圖片,能夠設置線性佈局
LinearLayout layout=new LinearLayout(getApplicationContext());
//設置LinearLayout垂直
layout.setOrientation(LinearLayout.HORIZONTAL);
//設置LinearLayout裏面內容中心分佈
layout.setGravity(Gravity.CENTER);
//先添加image
layout.addView(imageView);
//再添加text
layout.addView(textView);
//設置背景爲圓角邊框
layout.setBackground(getResources().getDrawable(R.drawable.message_bg));
//設置內邊距
layout.setPadding(30, 20, 30, 20);

//把layout設置進入Toast
toast.setView(layout);
//設置Toast位置居中
toast.setGravity(Gravity.CENTER,0,0);
//設置顯示時間
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();

圓角邊框背景

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <corners android:radius="10dp"/>
            <solid android:color="#b94bb4dd"/>
        </shape>
    </item>
</selector>
相關文章
相關標籤/搜索