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

问题描述 投票:48回答:6

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

Toast.makeText(getBaseContext(), "Please Enter Price", Toast.LENGTH_SHORT).show();

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

android android-layout toast
6个回答
22
投票

您可以创建自定义Toast view以满足您的要求。请参阅http://developer.android.com/guide/topics/ui/notifiers/toasts.html上标题为“创建自定义Toast视图”的部分


120
投票

您可以通过修改默认Toast来创建自定义布局,从而轻松实现此目的:

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中找到默认吐司视图使用的布局:

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


15
投票

您可能想要创建自定义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();

Source


7
投票

更改吐司背景颜色和吐司文本背景颜色的最简单方法:

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();

4
投票

你也可以使用SpannableString。它还可以为部分字符串着色。

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();

2
投票

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.