Android:如何设置Toast文本的颜色

我使用以下代码作为if语句的结果显示吐司消息:

Toast.makeText(getBaseContext(),“请input价格”,Toast.LENGTH_SHORT).show();

它在白色背景上显示为白色文字,因此无法阅读! 我的问题是,我怎样才能改变吐司文字的颜色?

您可以非常轻松地实现这一点,而无需通过修改默认的Toast来创build自定义布局:

Toast toast = Toast.makeText(this, resId, Toast.LENGTH_SHORT); TextView v = (TextView) toast.getView().findViewById(android.R.id.message); v.setTextColor(Color.RED); toast.show(); 

您可以在Android SDK中find默认的Toast视图使用的布局:

$ Android的SDK $ /平台/ Android的8 /数据/ RES /布局/ transient_notification.xml

您可能想要创build一个自定义Toast

 <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="10dp" android:background="#DAAA" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout> 

 LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.android); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Hello! 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(); 

资源

最简单的方法来改变一个吐司的背景颜色和一个吐司的文本的背景颜色:

 View view; TextView text; Toast toast; toast.makeText(this, resId, Toast.LENGTH_SHORT); view = toast.getView(); text = (TextView) view.findViewById(android.R.id.message); text.setTextColor(getResources().getColor(R.color.black)); text.setShadowLayer(0,0,0,0); view.setBackgroundResource(R.color.white); toast.show(); 

你也可以使用SpannableString 。 它也可以为string的一部分着色。

 SpannableString spannableString = new SpannableString("This is red text"); spannableString.setSpan( new ForegroundColorSpan(getResources().getColor(android.R.color.holo_red_light)), 0, spannableString.length(), 0); Toast.makeText(this, spannableString, Toast.LENGTH_SHORT).show(); 

尝试使用Toasty库。 它真的很容易使用 – https://github.com/GrenderG/Toasty

在这里输入图像说明