我为自定义 toast 创建了以下方法。
public void customToastMessage(String message){
LayoutInflater inf = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inf.inflate(R.layout.custom_toast_layout,(ViewGroup)findViewById(R.id.myCustomToast));
TextView toastMessage = layout.findViewById(R.id.myCustomToastText);
toastMessage.setText(message);
Toast warningMessage = Toast.makeText(con, message, Toast.LENGTH_LONG);
warningMessage.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 10);
warningMessage.setView(layout);
warningMessage.show();
}
只要这个方法存在于 MainActivity 中,它就可以正常工作,但是当我将它移动到一个单独的类时,我得到:
"java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)".
我需要在下面的类(class)中更改什么?
public class MyCustomUI extends AppCompatActivity {
private static Context con;
public MyCustomUI(Context con){
this.con = con;
}
public void customToastMessage(String message){
LayoutInflater inf = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inf.inflate(R.layout.custom_toast_layout,(ViewGroup)findViewById(R.id.myCustomToast));
TextView toastMessage = layout.findViewById(R.id.myCustomToastText);
toastMessage.setText(message);
Toast warningMessage = Toast.makeText(con, message, Toast.LENGTH_LONG);
warningMessage.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 10);
warningMessage.setView(layout);
warningMessage.show();
}
}
最佳答案
我猜你的问题是当你膨胀你的布局时:
View layout = inf.inflate(R.layout.custom_toast_layout,(ViewGroup)findViewById(R.id.myCustomToast));
我也猜测问题是 (ViewGroup)findViewById(R.id.myCustomToast)
。您正在尝试查找该类中不存在但在您的 MainActivity 中存在的 View/ViewGroup。
将其作为参数传递给您的方法(只是相关部分):
public void customToastMessage(String message, ViewGroup customToast){
LayoutInflater inf = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inf.inflate(R.layout.custom_toast_layout, viewgroup);
关于java - Android 自定义 toast 消息不能在单独的类中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52300451/