Search code examples
androidonclicklistenertoastbuttonclickandroid-toast

Can I add Click Listener to a custom Toast


I am creating a custom toast for my application. What I need is to add OnClickListener on a button I added on Toast. Everything goes well, I can see the button but it does not respond to OnClick. Any idea.

Example Code:

Button button = new Button(getApplicationContext());
            button.setText("Click Me");
            button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ProgressDialog.show(getApplicationContext(), "Hello", "nothing");

                }
            });
        button.setLayoutParams(new     ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.setMargin(0,-80);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(button);  
        toast.show();

Further, I have tried by adding onTouchListener to button like this.

 button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ProgressDialog.show(getApplicationContext(), "Hello", "nothing");
        return false;
    }
});

But it does not work either.


Solution

  • Crouton library solved the problem. Hope it would be helpful for someone else too.

    https://github.com/keyboardsurfer/Crouton