如何在Android中自定义Toast的背景,背景颜色和文本颜色

前端之家收集整理的这篇文章主要介绍了如何在Android中自定义Toast的背景,背景颜色和文本颜色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想通过修改默认Toast来自定义我的吐司而不创建自定义布局.我希望红色为吐司的背景,白色为吐司的文字颜色,我想让我的吐司的背景更大,默认吐司.当我运行我的应用程序时,我的吐司没有任何变化,它仍然显示在默认的吐司中.

这就是我自定义吐司的方式:

  1. if (seriesSelection == null) {
  2. Toast toast = Toast.makeText(getApplicationContext(),"tidak ada chart yang dipilih",Toast.LENGTH_SHORT);
  3. toast.setGravity(Gravity.CENTER,50,50);
  4. toast.getView().setPadding(10,10,10);
  5. toast.getView().setBackgroundColor(Color.RED);
  6. TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
  7. text.setTextColor(Color.WHITE);
  8. text.setTextSize(14);
  9. } else {
  10. Toast toast= Toast.makeText(
  11. getApplicationContext(),"Nilai " + listData.get(seriesSelection.getPointIndex()).getInuNilai()+
  12. " tanggal " + listData.get(seriesSelection.getPointIndex()).getTanggal(),Toast.LENGTH_SHORT);
  13. toast.setGravity(Gravity.CENTER,10);
  14. toast.getView().setBackgroundColor(Color.RED);
  15. text.setTextColor(Color.WHITE);
  16. text.setTextSize(14);
  17. toast.show();
  18. }

解决方法

您可以使用自定义视图为自定义视图充气并使用toast.setView(布局).

例:

  1. LayoutInflater inflater = getLayoutInflater();
  2. View layout = inflater.inflate(R.layout.custom_toast,(ViewGroup) findViewById(R.id.toast_layout_root));
  3.  
  4. TextView text = (TextView) layout.findViewById(R.id.text);
  5. text.setText("This is a custom toast");
  6.  
  7. Toast toast = new Toast(getApplicationContext());
  8. toast.setGravity(Gravity.CENTER_VERTICAL,0);
  9. toast.setDuration(Toast.LENGTH_LONG);
  10. toast.setView(layout);
  11. toast.show();

还有你的xml

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:id="@+id/toast_layout_root"
  3. android:orientation="horizontal"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:padding="8dp"
  7. android:background="#DAAA"
  8. >
  9. <ImageView android:src="@drawable/droid"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:layout_marginRight="8dp"
  13. />
  14. <TextView android:id="@+id/text"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:textColor="#FFF"
  18. />
  19. </LinearLayout>

更多信息 @

http://developer.android.com/guide/topics/ui/notifiers/toasts.html

在你的if和else部分代码(单独)中显示它以红色背景和白色文本颜色显示吐司.我没有看到任何问题.但是,如果您需要自定义,可以使用自定义布局并使布局膨胀并将视图设置为toast.

编辑:

你的textview

  1. TextView text = (TextView) toast.getView().findViewById(android.R.id.message);

在if部分初始化,而在其他部分textview未初始化.

在if和else代码之外初始化textview.

检查这个名为crouton的库,您可能会发现它很有用

https://github.com/keyboardsurfer/Crouton

猜你在找的Android相关文章