I just need to override show() for the Toast class

后端 未结 2 845
北海茫月
北海茫月 2021-01-23 22:50

I just need to override the show() method for the Toast class. I created a class which extends Toast class, but then I create a toast mess

相关标签:
2条回答
  • 2021-01-23 23:23

    More easy way :

    public class MyToast extends Toast { 
    public MyToast(Context context){ 
    super(context)
    this.setView(LayoutInflater.from(context).inflate(R.layout.activity_toast,null));
    }
    public void showMe(){
    super.show();
    }
    public static MyToast myMakeText(Context con,String message,int duration) { 
    MyToast mts = new MyToast(con); 
    View view = mts.getView(); 
    TextView messageArea = view.findViewById(R.id.toastTextView);
     messageArea.setText(message);
     mts.setDuration(duration);
    return mts;
    }}
    

    So you will ask :

    MyToast.myMakeText(this,"my message",7000).showMe();
    
    0 讨论(0)
  • 2021-01-23 23:38

    Did you call super.show() within your override? It's likely that Toast.show() is calling this, and your override is now making it so that the call doesn't happen.

    What you'll probably need to do is something like this:

    public class MyOwnToast extends Toast {
        public MyOwnToast(Toast toast) {
            //Code to initialize your toast from the argument toast
    
            //Probably something like this:
            this.setView(toast.getView());
            this.setDuration(toast.getDuration());
            //etc. for other get/set pairs in Toast
        }
    
        public static MyMakeText(Context context, CharSequence text, int duration) {
            return new MyOwnToast(Toast.makeText(context, text, duration));
        }
    
        public void show() {
            //Your show override code, including super.show()
        }
    }
    

    Then, when you want to use it, do:

    MyOwnToast.MyMakeText(activity, "Some text", Toast.LENGTH_LONG).show();
    

    See the Toast docs as a reference when filling this out: http://developer.android.com/reference/android/widget/Toast.html

    0 讨论(0)
提交回复
热议问题