android - 如何在没有多个背景 xml 的情况下更改自定义 toasts 消息的背景?
问题描述
我想更改自定义 toast 消息的背景,但我不想为每种颜色创建一个新的 xml 文件。进一步来说;
这是我在可绘制目录下的custom_toast_border.xml文件。
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content"
android:layout_width="match_parent">
<stroke android:width="1dp" android:color="@color/toastGreen" />
<corners android:radius="0dp" />
<gradient android:startColor="@color/toastGreen"
android:endColor="@color/toastGreen"
android:angle="-90"/>
我的custom_toast.xml布局就是这样
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@drawable/custom_toast_border"
android:layout_gravity="bottom|center_horizontal"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp">
<TextView
android:id="@+id/tv_toast_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="@font/futura_book"
android:padding="3dp"
android:text="Toast Message"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
Java代码:
..... inflater = getLayoutInflater();
layout = inflater.inflate(R.layout.custom_toast,null);
toast_message = layout.findViewById(R.id.tv_toast_message);
Toast toast = new Toast(getActivity().getApplicationContext());
//View view = toast.getView(); //It is failed. Null object referance
//view.getBackground().setColorFilter(getResources().getColor(R.color.toastRed), PorterDuff.Mode.SRC_IN);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
我想为吐司背景设置三种不同的颜色。我必须为每种颜色创建单独的文件吗?(如 custom_toast_border_red、..._green、.._yellow)。我不能从 java 代码中更改背景颜色吗? 请注意,我不想改变文字颜色,我想改变背景颜色。以前问题的大多数答案都解释了如何更改文本颜色。
解决方案
GradientDrawable containerDrawable = (GradientDrawable) layout.findViewById(R.id.custom_toast_container).getBackground();
containerDrawable.setColor(Color.GREEN); // CHANGE BG COLOR
containerDrawable.setStroke(1,Color.GREEN); // CHANGE THE STROKE COLOR
推荐阅读
- c - 如何对包含多个字符串的结构应用基数排序(使用计数排序)
- apache - 只允许从它们所在的网站访问目录中的文件
- selenium - selenium 与 javascript 的 firefox 关闭选项卡,但 SetTimeout() 不正常
- java - 如何在不重新加载页面的情况下提交表单
- node.js - 如何使用 Node 从远程服务器获取数据
- javascript - 用python和react js创建一个electron JS桌面应用
- upgrade - 从 Artifactory 2.3.3.1 升级
- docker - 无法使用撰写文件版本 2.4 部署 docker 堆栈
- perl - Perl:表达式优先级和评估
- javascript - 浏览器关闭时如何删除cookies?ASP.Net 核心,C#