Java Android自定义Toast消息在单独的类中不起作用
我为自定义toast创建了以下方法Java Android自定义Toast消息在单独的类中不起作用,java,android,toast,android-toast,Java,Android,Toast,Android Toast,我为自定义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.
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:无法在android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)上执行android的方法:onClick”
我需要在下面的课堂上改变什么
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();
}
}
我猜你的问题是当你膨胀布局时: 视图布局=inf.flate(R.layout.custom_toast_布局,(视图组)findviewbyd(R.id.myCustomToast)) 我还猜问题出在
(ViewGroup)findviewbyd(R.id.myCustomToast)
。您试图查找的视图/视图组不存在于该类中,但存在于MainActivity中
将其作为参数传递给方法(仅相关部分):
在MainActivity中调用该方法时,作为ViewGroup customToast?(ViewGroup)findViewById(R.id.myCustomToast)的参数传递什么
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);