Я делаю приложение в Android Studio. Я использовал SharedPreferenced для изменения статуса кнопки (Enable), и он работает, но я хочу также изменить фон кнопки (entrycity -> имя этой кнопки) с помощью моего 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();
}
}
}
Вы можете сохранить идентификатор фонового ресурса в своем sharedPreference как integer. А затем установите его на свою кнопку, используя
entrycity.setBackgroundResource(sharedPreferences.getInt("myBgId",R.drawable.default_id));
Как сохранить фон как целое число? Как должен выглядеть мой код?
если вы хотите, чтобы пользовательский фон можно было рисовать:
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));
}
button.setBackgroundResource (R.drawable.yourbackground);