单击另一个按钮时永久启用一个按钮。即使应用程序重新启动

Permanently Enabling a Button when another Button is Clicked. Even the app is restarted

我有 2 个按钮 Btn1 和 Btn2。 Btn2 已禁用但是当单击 Btn1 时 Btn2 应该永久启用,即使应用程序已重新启动

按钮 Btn1,Btn2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Btn1 = (Button)findViewById(R.id.EnabledBtn);
    Btn2 = (Button)findViewById(R.id.disbledBtn);

    Btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            pref.edit().putBoolean("isEnabled",false).apply();
            Btn2.setEnabled(true);
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    boolean enabled = pref.getBoolean("isEnabled",true);
    Btn2.setEnabled(enabled);


}

}

将您的代码更改为


SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);

    Btn1 = (Button)findViewById(R.id.EnabledBtn);
    Btn2 = (Button)findViewById(R.id.disbledBtn);

  /*when the app is launched, it will check if the button should be 
    enabled by getting the value from sharedpreferences. If the value was 
    not already set, then it chooses false as the default value*/

    boolean enabled = pref.getBoolean("isEnabled",false);
    Btn2.setEnabled(enabled);

  /*When btn1 is clicked, you want to store value true to 
    sharedpreferences so that it will be the value that will be 
    retrieved when app is restarted*/

    Btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pref.edit().putBoolean("isEnabled",true).apply();
            Btn2.setEnabled(true);
        }
    });
}

请查看代码中的注释以了解为什么需要进行更改。