片段中的自定义吐司

时间:2014-11-07 19:18:36

标签: android android-fragments android-toast

我有简单的自定义吐司,它在类范围活动中工作正常,但在片段我有一个问题。 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();

2 个答案:

答案 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();