android定制敬酒

时间:2012-12-30 08:17:11

标签: android toast

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

    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”..

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

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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();

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

谢谢