我有简单的自定义吐司,它在类范围活动中工作正常,但在片段我有一个问题。
findviewbyid方法dosn工作片段!!
我该如何解决?
LayoutInflater inflater = getLayoutInflater();
View layouttoast = inflater.inflate(R.layout.customtoast, (ViewGroup)findViewById(R.id.toastcustom));
((TextView) layouttoast.findViewById(R.id.texttoast)).setText(message);
layouttoast.findViewById(R.id.imagetoast)).setBackgroundResource(R.drawable.icon);
Toast mytoast = new Toast(getBaseContext());
mytoast.setView(layouttoast);
mytoast.setDuration(Toast.LENGTH_LONG);
mytoast.show();
答案 0 :(得分:5)
您应该将代码放在onCreateView
的{{1}}方法下,然后从查看片段膨胀的方式调用Fragment
方法,如下所示:
findViewById
答案 1 :(得分:1)
尝试这个并相应地更改布局和ID:
LayoutInflater inflater1 = getActivity().getLayoutInflater();
View layout = inflater1.inflate(R.layout.custom_toast, (ViewGroup) getActivity().findViewById(R.id.custom_toast_layout_id));
// set a message
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Custom Toast");
// Toast...
Toast toast = new Toast(getActivity().getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();