【发布时间】: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