Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change text in a Toast Notification dynamically while it's being displayed?

Tags:

android

toast

I seek to create a toast whose value should reflect a number and should dynamically change while the toast is still displayed. I don't want to create new toasts for every change in the value. The changes to the value should reflect in the existing displayed toast itself. Is this possible, if so, how should I go about it?

like image 391
Debojeet Chatterjee Avatar asked Dec 25 '22 01:12

Debojeet Chatterjee


1 Answers

You can save your instance of Toast which you get from makeText and update it with setText.

UPDATED

Code:

public class MainActivity extends ActionBarActivity {

    private Toast mToast;

    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.toast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (mToast == null) {
                    mToast = Toast.makeText(MainActivity.this, "Count " + 0, Toast.LENGTH_LONG);
                }
                mToast.setText("Count " + count++);
                mToast.show();
            }
        });
    }   
}
like image 98
Bracadabra Avatar answered Dec 27 '22 15:12

Bracadabra