我正在尝试创建一个 Helper 类来在我的 Android 应用程序中显示 Toast,如下所示。
公共(public)类 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
我的问题是,当我尝试膨胀 View 时,如果没有我调用 toastAlert 的 Activity 中的 View ,我无法调用 findViewById。有没有办法可以访问该 View ?
最佳答案
我唯一的想法是将 View 传递到方法中。事情不会那么糟糕,一切看起来像这样:
class.toastAlert(this, "My Toast");
关于java - Android Toast 和查看帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1942236/