I set a button on layout, and if user click button that will display toast...

button.setOnClickListener(toastListener);
OnClickListener toastListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub  
        Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
        error.show();
    }
};

But when user click button many time, they will display more toast.
Can I always display one toast on screen whether how many times user click button?
Thanks a lot

有帮助吗?

解决方案

I haven't tried it for real but I suspect just cancelling it on the next click and making a new one would be alright.

Toast mToast;

public void onContentChanged() {
  ...
  button.setOnClickListener(toastListener);
  OnClickListener toastListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        if(mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
        mToast.show();
    }
  };

其他提示

I use the following method to achieve this.

private void showToastMessage(final String message) {
            mHandler.post(new Runnable() {
                public void run() {
                    if (mToast == null) {
                        if (getActivity() != null) {
                            mToast = Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT);
                        }
                    }
                    if (getActivity() != null) {
                        mToast.setText(message);
                        mToast.show();
                    }
                }
            }); 
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top