gpt4 book ai didi

java - 如何在android中为Toast自定义背景、背景颜色和文字颜色

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:08 29 4
gpt4 key购买 nike

我想通过修改默认 Toast 来自定义我的 Toast,而不创建自定义布局。我想要 toast 背景为红色, toast 文本颜色为白色,我想让我的 toast 背景比默认 toast 更大。当我运行我的应用程序时,我的 toast 没有任何变化,它仍然显示在默认 toast 中。

这就是我自定义 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, 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, 50, 50);
toast.getView().setPadding(10, 10, 10, 10);
toast.getView().setBackgroundColor(Color.RED);
text.setTextColor(Color.WHITE);
text.setTextSize(14);
toast.show();
}

最佳答案

您可以让自定义 View 膨胀自定义 View 并使用 toast.setView(layout)

示例:

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, 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。我看不出有什么问题。但如果您需要自定义,您可以使用自定义布局并扩充布局并将 View 设置为 toast。

编辑:

你的 TextView

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

在 if 部分初始化,在 else 部分 textview 未初始化。

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

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

https://github.com/keyboardsurfer/Crouton

关于java - 如何在android中为Toast自定义背景、背景颜色和文字颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17800953/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com