片段中的自定义吐司

max*_*max 0 android android-fragments android-toast

我有简单的自定义吐司,它在类范围活动中工作正常,但在片段中我有一个问题.findviewbyid方法不能在碎片中工作!!
我该怎么办呢?

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();
Run Code Online (Sandbox Code Playgroud)

rom*_*4ek 5

你应该把你的代码置于onCreateViewthe方法之下Fragment,然后findViewById从片段膨胀的视图中调用方法,如下所示:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View parent = inflater.inflate(R.layout.your_fragment_layout, container, false);

    View layouttoast = inflater.inflate(R.layout.customtoast,(ViewGroup)parent.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();
    return parent;
}
Run Code Online (Sandbox Code Playgroud)