微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Android中自定义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);
    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,10);
    toast.getView().setBackgroundColor(Color.RED);
    text.setTextColor(Color.WHITE);
    text.setTextSize(14);
    toast.show();
}

解决方法

您可以使用自定义视图为自定义视图充气并使用toast.setView(布局).

例:

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

编辑:

你的textview

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

在if部分初始化,而在其他部分textview未初始化.

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

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

https://github.com/keyboardsurfer/Crouton

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐