简体   繁体   English

设置活动中的可见和不可见按钮

[英]How visible and invisible button from settings activity

In my main activity there is button, I want to do visible or invisible from settings Activity,I Use switchPreferences在我的主要活动中有按钮,我想从设置活动中可见或不可见,我使用 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;
    }
});

In your MainActivity create the contract to receive the boolean value:在您的 MainActivity 中创建合同以接收 boolean 值:

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:要导航到您的 SettingsActivity,必须在 MainActivity 中执行合同:

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

And in your SettingsActivity propagate the result:并在您的 SettingsActivity 中传播结果:

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并且有必要在 SettingsActivity 中执行finish()以传播结果

I think there are two ways to achieve this.我认为有两种方法可以实现这一目标。

A) Hacky way, only should be used with very simple application scenario A)Hacky方式,只适用于非常简单的应用场景

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.如果你有一个非常小的应用程序,根本不会经常使用 SettingsActivity,你可以设置退出 SettingsActivity 后重新创建 MainActivity,从而更新整个 UI。 For that, add this method to the SettingsActivity:为此,将此方法添加到 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:在 MainActivity 中,您只需像往常一样设置按钮的可见性:

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:因此,如果您想要一种干净且可扩展的方法,我会向 go 推荐第二种解决方案:

B) Clean way using onActivityResult B)使用 onActivityResult 的清洁方式

To to this, add the following code at the point where the SettingsActivity is started from your MainActivity:为此,请在从 MainActivity 启动 SettingsActivity 的位置添加以下代码:

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

The constant REQUEST_CODE_SETTINGSACTIVITY is a constant that has value assigned.常量REQUEST_CODE_SETTINGSACTIVITY是一个已赋值的常量。 The value itself is unimportant, it's just some sort of ID for the result.值本身并不重要,它只是结果的某种 ID。 So declare it on top of your MainActivity like this:所以像这样在你的 MainActivity 上声明它:

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

In your SettingsActivity, add the following code.在您的 SettingsActivity 中,添加以下代码。
The boolean randomColorValue is a global boolean that will be set to true or false to represent the current setting: boolean randomColorValue是一个全局 boolean 将设置为 true 或 false 以表示当前设置:

@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.请注意,您应该从此方法返回true By doing so, the SwitchPreference will automatically be updated, so no need to manually update it.这样一来,SwitchPreference 将自动更新,因此无需手动更新。

Finally add the following method to the SettingsActivity:最后在 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.然后回到您的 MainActivity,添加以下方法。 Note that for that, your Acitivity needs to extend FragmentActivity or AppCompatActivity :请注意,为此,您的 Acitivity 需要扩展FragmentActivityAppCompatActivity

@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.每次 go 到 SettingsActivity 并从它返回时,都会调用 onActivityResult 方法,然后相应地设置按钮的可见性。

Note that I am not able to verify this solution right now, but this should be for about the direction to go.请注意,我现在无法验证此解决方案,但这应该是关于 go 的方向。 If this answer was helpful, you can accept it by clicking the green checkmark next to it.如果此答案有帮助,您可以通过单击旁边的绿色复选标记来接受它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM