java - Android Toast 和查看帮助

标签 java android

我正在尝试创建一个 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/

相关文章:

java - 在我的应用程序中膨胀类 android.support.design.widget.NavigationView 时出错

java - 如果墙纸是从另一个应用程序设置的,如何停止服务

java - Buck exopackage 多 dex 支持?

java - 如何在java中获取签名的url?

java - Spock Spring 通过构造函数注入(inject)模拟和 bean

java - ClassCastException : Fragment cannot be cast to Fragment

android - Xamarin 表单导航后退按钮

java - 在 Android 模拟器中以 "Airplane"模式进行测试

java - 使用 S3 Java SDK 与 S3 兼容存储(minio)对话

java - 2 人井字游戏