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

╄→гoц情女王★ 提交于 2019-11-30 23:09:03

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();
            }
        });
    }   
}

These other answers weren't working for me. Maybe its Oreo. This is what people are looking for. Should work in all cases.

EDIT: It should be clarified that original toast will only show as long as the duration allows it. Once the toast length is finished, you cannot call show() on it without re-instantiation.

    private Toast mToast;
    protected void showToast(int value) {

        if (mToast == null) {
            mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
        } else {
            mToast.cancel();
            mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
        }

        mToast.setText("Shutdown in "+value+" seconds");
        mToast.show();
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!