Android Studio / 如何将 SharedPpreferred 应用于我的代码



我在Android Studio做测验。游戏分为两类。传递第一个类别后,第二个按钮(打开第二个类别(将状态从 setEnable "false" 更改为 "true"。如何在我的代码中使用共享首选项方法,以便在关闭应用程序后保存与第二个按钮 (.setEnable( 相关的更改。

第一类的最后一级

public class win extends AppCompatActivity implements View.OnClickListener{
Button win1;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_winflagi);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
win1 = (Button) findViewById(R.id.winflagi);
win1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v==win1)
{
Intent myIntent = new Intent(win.this, Activity2.class);
myIntent.putExtra("isEnabled", "enabled");
startActivity(myIntent);
}
}
}
  • 类包含两个类别的按钮...
  • 按钮3打开了第一个类别
  • 入口城市开启第二类

    public class Activity2 extends AppCompatActivity implements View.OnClickListener{
    Button button3;
    Button entrycity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_2);
    button3 = (Button) findViewById(R.id.button3);
    button3.setOnClickListener(this);
    entrycity = (Button) findViewById(R.id.entrycity);
    entrycity.setOnClickListener(this);
    }
    @Override
    public void onClick(final View v) {
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.menu);
    if (v == button3) {
    startActivity(new Intent(Activity2.this, flagi1.class));
    Bungee.zoom(this);
    mp.start();
    }
    if (v== entrycity){
    Intent intent=getIntent();
    String isEnabled = intent.getStringExtra("isEnabled");
    if(isEnabled==null||isEnabled.equals("disabled")){
    entrycity.setEnabled(false);
    }
    else{
    entrycity.setEnabled(true);
    startActivity(new Intent(this, cities1.class));
    }
    }
    }
    }
    

在启用按钮时设置布尔首选项。

else{
entrycity.setEnabled(true);
getSharedPreferences("MY_PREF", MODE_PRIVATE).edit().putBoolean("isEnabled",true).apply();
startActivity(new Intent(this, cities1.class));
}

并在您的onCreate中根据首选项设置按钮的启用状态:

entrycity.setEnabled(getSharedPreferences("MY_PREF", MODE_PRIVATE).getBoolean("isEnabled",false));

最新更新