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

sup*_*per 49 android toast android-layout

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

Toast.makeText(getBaseContext(), "Please Enter Price", Toast.LENGTH_SHORT).show();
Run Code Online (Sandbox Code Playgroud)

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

XGo*_*het 123

您可以通过修改默认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();
Run Code Online (Sandbox Code Playgroud)

您可以在Android SDK中找到默认吐司视图使用的布局:

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

  • 你也可以做`toast.getView().setBackgroundColor(Color.RED);`来设置整个Toast区域的背景颜色. (61认同)
  • ^- 在我的电话上,虽然在默认的灰色背景后面添加了背景。 (2认同)

Man*_*del 22

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


Bra*_*ash 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>
Run Code Online (Sandbox Code Playgroud)

-

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();
Run Code Online (Sandbox Code Playgroud)

资源


Aks*_*nde 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();
Run Code Online (Sandbox Code Playgroud)


Ana*_*uba 5

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

在此处输入图片说明