有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 安卓 Toast和视图帮助

我正试图创建一个助手类来在我的安卓应用程序中显示祝酒词,如下所示

公务舱{

final static Toast toastAlert(String msg) {
    LayoutInflater inflater = LayoutInflater.from(Main.self.getApplicationContext());
    View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

    TextView tv = (TextView)layout.findViewById(R.id.toast_text);
    tv.setText(msg);

    Toast toast = new Toast(Main.self.getApplicationContext());
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setView(layout);
    return toast;
}

}

<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
          安卓:id="@+id/toast_layout_root"
          安卓:orientation="horizontal"
          安卓:layout_width="fill_parent"
          安卓:layout_height="fill_parent"
          安卓:padding="10dip"
          安卓:background="#FFF"
          >
<TextView 安卓:id="@+id/toast_text"
          安卓:layout_width="wrap_content"
          安卓:layout_height="fill_parent"
          安卓:textColor="#000"
          />

我的代码基于以下示例:http://developer.安卓.com/guide/topics/ui/notifiers/toasts.html

我的问题是,当我尝试膨胀视图时,如果没有我调用的活动中的视图,我无法调用findViewById。有什么方法可以访问该视图吗


共 (2) 个答案

  1. # 1 楼答案

    我唯一的想法是将一个视图传递到该方法中。这不会太糟糕,一切都是这样的:

    class.toastAlert(this, "My Toast");
    
  2. # 2 楼答案

    我使用它来获取LayoutInflator

     LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
    

    我不知道这是否有用