如何在显示时动态更改 Toast 通知中的文本?

问题描述:

我试图创建一个 toast,它的值应该反映一个数字,并且应该在 toast 仍然显示时动态更改.我不想为值的每次更改都创建新的 toast.对值的更改应反映在现有显示的 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?

您可以保存从 makeText 并使用 setText.

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

更新

代码:

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