如何将 Toast 样式设为主题?

9

我想通过编辑themes.xml来更改我的 App 中所有的 Toast。

我正在使用<item name="buttonStyle">@style/MyButton</item>来更改我的按钮,是否有类似的方法可以更改 Toast 呢?还是说我需要创建并使用一个扩展内置 Toast 的MyToast类?

2个回答

6
您可以使用以下代码更改Toast的背景色:
<style name="myTheme" parent="@android:styles/Theme.Holo">
  <item name="android:toastFrameBackground">@android:drawable/my_toast</item>
</style>

谢谢Ahmad,除了背景之外还有其他的自定义吗?另外,是否有一个包含所有项目名称的表格,比如android:toastFrameBackground - guness
1
@bluebrain,据我所知,你无法使用样式来设置重力等属性,必须通过编程实现。Android是开源的,因此你可以在这里找到所有内容:https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml - Ahmad
3
你能改变背景吗?正如其他SO帖子所指出的那样,toastFrameBackgound不是公共的。在API 18上,我收到一个错误,说没有找到与该名称匹配的资源。http://stackoverflow.com/questions/19215326/styles-toast-background-no-resource-found-that-matches-the-given-name - spaaarky21
1
我在SDK 27中找不到android:toastFrameBackground - AutonomousApps
这种方法并不适用于所有设备,因为“toastFrameBackground”不是公共API的一部分{https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/res/res/values/public.xml}。在所有设备上都能正常工作的安全解决方案就是使用`Toast.setView(view)`。 - Henry

-3

试试这个:

 Toast toast=new Toast(this);
     LayoutInflater inflater=this.getLayoutInflater();
     View toastView=inflater.inflate(R.layout.toast_layout, (ViewGroup)findViewById(R.id.toastView));
     TextView txtDate=(TextView)toastView.findViewById(R.id.txtDate);
     txtDate.setText("toast appeared at "+Calendar.getInstance().getTime().toLocaleString());
     toast.setGravity(Gravity.CENTER, 0, 0);
     toast.setView(toastView);
     toast.show();

8
请您详细说明答案,我没有看到与“主题”有关的内容(这与全局相关,而不是单个提示),请问您能否详细说明一下? - guness

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接