【问题标题】:android Toast and View helpandroid Toast 和查看帮助
【发布时间】:2009-12-21 19:55:29
【问题描述】:

我正在尝试创建一个 Helper 类来在我的 android 应用中显示 Toast,如下所示。

公共类 ToastHelper{

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:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/toast_layout_root"
          android:orientation="horizontal"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="10dip"
          android:background="#FFF"
          >
<TextView android:id="@+id/toast_text"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:textColor="#000"
          />

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

我的问题是,当我尝试膨胀视图时,如果没有来自我正在调用 toastAlert 的活动中的视图,我将无法调用 findViewById。有没有办法可以访问该视图?

【问题讨论】:

    标签: java android


    【解决方案1】:

    我唯一的想法是将 View 传递给方法。它不会那么糟糕,一切看起来像这样:

    class.toastAlert(this, "My Toast");
    

    【讨论】:

    • 我记得很多辅助函数最终都需要 View 或 Context,而最简单的处理方法就是传递它。
    【解决方案2】:

    我用它来获取LayoutInflator

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

    我不知道这是否有帮助。

    【讨论】: