【问题标题】:Custom Toast Inflating - Android自定义吐司充气 - Android
【发布时间】:2014-12-10 00:19:33
【问题描述】:

我正在创建名为 MyToast 的自定义 toast 类:

public class MyToast extends Toast {

    public static final int RED = 0;
    public static final int BLUE = 1;

    public MyToast(Context context, String data, int color) {
        super(context);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.my_toast, null);
        setView(layout);

        TextView tvToast = (TextView) layout.findViewById(R.id.tvToast);
        tvToast.setText(data);

        if(color == RED) {
            tvToast.setBackgroundResource(R.drawable.red_background);
            tvToast.setTextColor(context.getResources().getColor(R.color.red));
        } else {
            tvToast.setBackgroundResource(R.drawable.blue_background);
            tvToast.setTextColor(Color.WHITE);
        }
    }
}

my_toast.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <TextView
        android:id="@+id/tvToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

在 MainActivity 中使用 MyToast:

new MyToast(context, getResources().getString(
                            R.string.uspesna_najava), MyToast.BLUE).show();

我收到此警告:

避免将 null 作为视图根传递(需要解析布局 膨胀布局的根元素上的参数)

关于这部分代码:

View layout = inflater.inflate(R.layout.my_toast, null);

此代码运行良好,但我想摆脱该警告。 我知道我需要像这样充气,以避免出现此警告:

View layout = inflater.inflate(R.layout.my_toast, parent, false);

但我在哪里可以找到父母?

在官方网站Android Developers,他们这样夸大视图:

    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    View layout = inflater.inflate(R.layout.my_toast, (ViewGroup) findViewById(R.id.toast_layout_root));

我试过这样,但出现错误:

MyToast 类型的 findViewById(int) 方法未定义

【问题讨论】:

标签: android toast android-inflate


【解决方案1】:

当然,findViewById方法是Activity的方法。

所以示例代码在Activity类中,只要调用findViewById就没有问题。

因此您的代码在 MyToast 类中,您应该调用 Activity 实例的方法:

((Activity) context).findViewById(R.id.toast_layout_root)

【讨论】:

  • 我遇到了类似的问题。但是我传递的上下文来自服务而不是活动。有没有其他方法可以获取findViewById 方法?
猜你喜欢
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多