我正在Android Studio中制作一个应用。我使用SharedPreferenced来更改按钮状态(启用),并且可以使用,但我也想使用我的SharedPreferenced来更改按钮背景(输入->此按钮的名称)。怎么做?
这是我的代码
public class Activity2 extends AppCompatActivity implements View.OnClickListener{
Button button3;
Button entrycity;
private static final String NAME = "name";
private boolean isEnabled;
private SharedPreferences sharedPreferences;
@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);
sharedPreferences = getSharedPreferences(NAME, MODE_PRIVATE);
isEnabled = sharedPreferences.getBoolean(winflagi.IS_ENABLED, false);
entrycity.setEnabled(isEnabled);
}
@Override
public void onClick(final View v) {
final MediaPlayer mp = MediaPlayer.create(this, R.raw.menunew);
if (v == button3) {
startActivity(new Intent(Activity2.this, flagi1.class));
Bungee.zoom(this);
mp.start();
}
if (v.getId() == R.id.entrycity){
startActivity(new Intent(this, cities1.class));
Bungee.zoom(this);
mp.start();
}
}
}
答案 0 :(得分:0)
您可以将背景资源ID在您的sharedPreference中另存为integer
。然后使用
entrycity.setBackgroundResource(sharedPreferences.getInt("myBgId",R.drawable.default_id));
答案 1 :(得分:0)
如果要自定义背景可绘制对象:
if(isEnable){
btnAccountStatus.setBackground(ContextCompat.getDrawable(this, R.drawable.YourDrawableEnable));
} else {
btnAccountStatus.setBackground(ContextCompat.getDrawable(this, R.drawable.YourDrawableDisable));
}
如果您想要自定义背景色:
if(isEnable){
btnAccountStatus.setBackgroundColor(ContextCompat.getDrawable(this, R.color.YourColorEnable));
} else {
btnAccountStatus.setBackgroundColor(ContextCompat.getDrawable(this, R.color.YourColorDisable));
}