Home > database >  How visible and invisible button from settings activity
How visible and invisible button from settings activity

Time:02-02

In my main activity there is button, I want to do visible or invisible from settings Activity,I Use switchPreferences

My settingsActivity

final SwitchPreference onOffRandomColor = (SwitchPreference) findPreference("floting_button");
    
onOffRandomColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
    @SuppressLint("NewApi")
    @Override
    public boolean onPreferenceChange(Preference preference, Object o) {
        if (onOffRandomColor.isChecked()) {
            Toast.makeText(getContext(),"Unchecked",Toast.LENGTH_SHORT).show();
            onOffRandomColor.setChecked(false);
        } else {
            Toast.makeText(getContext(),"Checked",Toast.LENGTH_SHORT).show();
            onOffRandomColor.setChecked(true);
        }
        return false;
    }
});

CodePudding user response:

I think there are two ways to achieve this.

A) Hacky way, only should be used with very simple application scenario

In case you have a really small application, where the SettingsActivity will not be used often at all, you just can set that after exiting the SettingsActivity, the MainActivity will be recreated, so the whole UI will be updated. For that, add this method to the SettingsActivity:

@Override
public void onBackPressed() {

    // With this code, MainActivity will be restarted. All other activities will
    // be cleared from the stack.
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}

And in the MainActivity, you just set the visibility of the button as usual:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean randomColorValue = prefs.getBoolean("floting_button", false);
myButton.setVisibility(randomColorValue ? View.VISIBLE : View.INVISIBLE);

One drawback is that the previous activity will be restarted even if no setting was changed at all. So I would recommend to go with the second solution, if you want a clean and scalable approach:

B) Clean way using onActivityResult

To to this, add the following code at the point where the SettingsActivity is started from your MainActivity:

Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivityForResult(intent, REQUEST_CODE_SETTINGSACTIVITY);

The constant REQUEST_CODE_SETTINGSACTIVITY is a constant that has value assigned. The value itself is unimportant, it's just some sort of ID for the result. So declare it on top of your MainActivity like this:

public static final REQUEST_CODE_SETTINGSACTIVITY = 1;  // or any other number

In your SettingsActivity, add the following code.
The boolean randomColorValue is a global boolean that will be set to true or false to represent the current setting:

@Override
public boolean onPreferenceChange(Preference preference, Object o) {
    if (onOffRandomColor.isChecked()) {
        Toast.makeText(getContext(),"Unchecked",Toast.LENGTH_SHORT).show();
        randomColorValue = false;
    } else {
        Toast.makeText(getContext(),"Checked",Toast.LENGTH_SHORT).show();
        randomColorValue = true;
    }
    return true;
}

Note that you should return true from this method. By doing so, the SwitchPreference will automatically be updated, so no need to manually update it.

Finally add the following method to the SettingsActivity:

@Override
public void onBackPressed() {

    // at exit, we pass the boolean value to the intent, 
    // so in MainActivity we can receive it
    Intent resultIntent = new Intent();
    resultIntent.putExtra("randomColorValue", randomColorValue);
    setResult(Activity.RESULT_OK, resultIntent);
    finish();

}

And back in your MainActivity, add the following method. Note that for that, your Acitivity needs to extend FragmentActivity or AppCompatActivity:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE_SETTINGS) {
        if (resultCode == Activity.OK) {
            if (data != null) {
                // now we can get the value that we set in the SettingsActivity
                boolean randomColorValue = data.getBooleanExtra("randomColorValue", false);
                myButton.setVisibility(randomColorValue ? View.VISIBLE : View.INVISIBLE);
            }
        } 
    }
}

Each time you go to the SettingsActivity, and return from it, the onActivityResult method will be called, and then the visibility of the button is set accordingly.

Note that I am not able to verify this solution right now, but this should be for about the direction to go. If this answer was helpful, you can accept it by clicking the green checkmark next to it.

CodePudding user response:

In your MainActivity create the contract to receive the boolean value:

private final ActivityResultLauncher<Intent> settingsActivityLauncher = registerForActivityResult(new StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
    @Override
    public void onActivityResult(ActivityResult result) {
        if (result.getResultCode() == Activity.RESULT_OK) {
            Intent intent = result.getData();
            // Fetch the boolean value from intent and change the visibility button 
        }
}});

To navigate to your SettingsActivity, is necessary execute the contract in the MainActivity:

    settingsActivityLauncher.launch(new Intent(this, YourSettingsActivity.class));

And in your SettingsActivity propagate the result:

onOffRandomColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
    @SuppressLint("NewApi")
    @Override
    public boolean onPreferenceChange(Preference preference, Object o) {
        Intent resultIntent = new Intent();
        Boolean isButtonEnabled;
        if (onOffRandomColor.isChecked()) {
            onOffRandomColor.setChecked(false);
            isButtonEnabled = false;
        } else {
            onOffRandomColor.setChecked(true);
            isButtonEnabled = true;
        }

        resultIntent.putExtra("ARG_YOUR_KEY", isButtonEnabled); 
        setResult(RESULT_OK, resultIntent);  

        return false;
    }
});

And it is necessary to do finish() in the SettingsActivity to propagate the result

  •  Tags:  
  • Related