6

我能够使用此代码制作自定义吐司

    LayoutInflater inflater = getLayoutInflater();

    View layout = inflater.inflate(R.layout.custom_toast_layout, (ViewGroup)findViewById(R.id.custom_toast));

    TextView text = (TextView) layout.findViewById(R.id.toast_tv);
    text.setText("Hello! This is a custom toast!");

    Toast toast = new Toast(getApplicationContext());       
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();

但是,由于我不明白 的目的LayoutInflater,我将代码修改为...

Toast toast = new Toast(getApplicationContext());
    toast.setView(findViewById(R.id.custom_toast));
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.show();

我得到 RuntimeException 说“必须调用 setView”..

  • 为什么我不能在不使用的情况下将视图分配给 toast LayoutInflater

  • 一般的目的是什么,LayoutInflater以便我可以将此体验应用于其他自定义视图?

编辑: 我在onListItemClick()接口方法中使用这些代码..设置内容后..

4

2 回答 2

2

你的问题有你的答案,每个自定义视图都应该先膨胀,这就是你修改后的代码出错的原因。

于 2012-12-30T08:35:11.407 回答
1
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

这也是你所做的,它是完整的正确代码,你有你的答案,为了分配自定义视图,我们必须先使用自定义视图。

谢谢

于 2012-12-30T08:37:43.547 回答