我想通过修改默认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);
- 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,10);
- toast.getView().setBackgroundColor(Color.RED);
- text.setTextColor(Color.WHITE);
- text.setTextSize(14);
- toast.show();
- }
解决方法
您可以使用自定义视图为自定义视图充气并使用toast.setView(布局).
例:
- 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);
- 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.
编辑:
你的textview
- TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
在if部分初始化,而在其他部分textview未初始化.
在if和else代码之外初始化textview.
检查这个名为crouton的库,您可能会发现它很有用