我想自定义我的toast,而不需要通过修改默认toast来创建自定义布局。我想要红色作为吐司的背景,白色作为吐司文本的颜色,并且我想要使我的吐司背景比默认的吐司更大。当我运行我的应用程序时,我的toast没有任何变化,它仍然显示在默认的toast中。
这就是我定制吐司的方式:
if (seriesSelection == null) {
Toast toast = Toast.makeText(getApplicationContext(), "tidak ada chart yang dipilih", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 50, 50);
toast.getView().setPadding(10, 10, 10, 10);
toast.getView().setBackgroundColor(Color.RED);
TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
text.setTextColor(Color.WHITE);
text.setTextSize(14);
} else {
Toast toast= Toast.makeText(
getApplicationContext(),
"Nilai " + listData.get(seriesSelection.getPointIndex()).getInuNilai()+
" tanggal " + listData.get(seriesSelection.getPointIndex()).getTanggal(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 50, 50);
toast.getView().setPadding(10, 10, 10, 10);
toast.getView().setBackgroundColor(Color.RED);
text.setTextColor(Color.WHITE);
text.setTextSize(14);
toast.show();
}
您可以使用自定义视图来扩展自定义视图并使用toast.setView(layout)
。
示例:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
以及您的xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:background="#DAAA"
>
<ImageView android:src="@drawable/droid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
/>
</LinearLayout>
更多信息@
http://developer.android.com/guide/topics/ui/notifiers/toasts.html
运行代码的if和else部分(分别),它显示红色背景和白色文本的toast。我看不出有什么问题。但是,如果您需要自定义,可以使用自定义布局,放大布局并将视图设置为toast。
编辑:
您的文本视图
TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
在if部分中初始化,而在else部分中,文本视图未初始化。
在if和else代码外部初始化textview。
查看这个名为crutton的库,你可能会发现它是有用的
https://github.com/keyboardsurfer/Crouton
Toast有一个setView()
方法。
您可以自定义Toast以显示任何视图。
我想说的是,与其试图在Toast中编辑视图,不如创建一个视图并将其弹出。
我有非常简单易用的代码来定制Toast。相应地,您也可以更改Toast的背景和文本颜色。
Toast toast = Toast.makeText(MainActivity.this, "Added successfully", Toast.LENGTH_LONG);
View view = toast.getView();
view.setPadding(20, 20, 20, 20);
view.setBackgroundResource(R.color.GREEN);
view.setTextColor(Color.RED);
toast.show();