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

问题描述 投票:1回答:1

我为自定义吐司创建了以下方法。

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的方法:onClick at android.support.v7.app.AppCompatViewInflater $ DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)”。

我下面的班级需要改变什么?

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();
    }
}
java android toast android-toast
1个回答
1
投票

我猜你的问题是当你夸大你的布局时:

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);
© www.soinside.com 2019 - 2024. All rights reserved.