Android自定义Toast消息在单独的类中不起作用

时间:2018-09-12 17:18:37

标签: java android toast android-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:无法在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();
    }
}

1 个答案:

答案 0 :(得分:1)

我猜你的问题是当你给布局充气的时候:

  

视图布局= 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);