Search code examples
androidpreferenceactivityandroid-toast

Need to display Toast right after click


I saw related posts like this - Disable the Asynchronous display of a Toast [duplicate] and I tried cancel() method from there, but they don't solve my problem. Maybe it is because some difference related with Preference Activity.

Please, help me improve my code so the Toast displays right after click.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.pref_screen);
    Context context = getApplicationContext();
    settings = PreferenceManager.getDefaultSharedPreferences(context);
    settings.registerOnSharedPreferenceChangeListener(this);
}

public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
    Toast theToast;
    theToast = Toast.makeText(this, "toast text", Toast.LENGTH_LONG);

    if(key.equals("checkbox_key")){
        theToast.show();
    }
    if (key.equals("checkbox_key")&& theToast != null){
        theToast.cancel();
    }
}

Solution

  • Your question is poorly worded, but I assume (after reading your code) what you're asking is how to cancel a currently displayed Toast when you check/uncheck a new box and want to display a new Toast right away in that case.

    The problem is that you're canceling the Toast that you just made, instead of the Toast that is being displayed, which you created earlier.

    Try storing the Toast in a member variable and canceling that instead. Something like:

    private Toast mCurrerntToast = null;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        //...
    }
    
    public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
        if(key.equals("checkbox_key")){
            //If there is a previous toast displayed, cancel it
            if(mCurrentToast != null){
                mCurrentToast.cancel();
            }
    
            //Display a new, more current Toast message
            mCurrentToast = Toast.makeText(this, "toast text", Toast.LENGTH_LONG);
            mCurrentToast.show();
        }
    }
    

    Let me know if my assumption of what you were asking about was wrong and I'll try to help more, but I'm pretty sure this is the problem you're trying to solve.