我一直尝试做的是在使用共享偏好按下时保存按钮的状态。当按钮是默认按钮时,它是白色的,但按下时,它是黑色的。即使我按下后退按钮或从其他活动或应用程序返回,我希望该按钮保持黑色。几天来我一直在努力解决这个问题,这让我觉得我的编程并不好。有人可以帮帮我吗?这是我的代码。
fb1 = (Button) findViewById(R.id.button1);
fb1.setBackgroundResource(R.drawable.not_pressed);
fb1.setOnClickListener(new OnClickListener() {
boolean isPressed = true;
//boolean isPressed1 = true;
@Override
public void onClick(View v) {
//isPressed = sharedPrefs.getBoolean("locked", false);
fb1.setEnabled(sharedPrefs.getBoolean("locked", true));
System.out.println("BOOL" + isPressed);
if (!isPressed) {
fb1.setBackgroundResource(R.drawable.not_pressed);
fr1 = 0;
//fb1.setEnabled(false);
//sharedPrefs.edit().putBoolean("locked", fb1.isEnabled()).commit();
} else {
fb1.setBackgroundResource(R.drawable.pressed);
fr1 = 128;
//fb1.setEnabled(true);
//savePreferences("locked", fb1.isEnabled());
sharedPrefs.edit().putBoolean("locked", fb1.isEnabled()).commit();
}
isPressed = !isPressed;
}
});
答案 0 :(得分:0)
首先创建一个常量类并在其中声明一个静态变量:
public class Constants(){
public static boolean isPressed = false;
}
现在,在Activity类中使用此静态变量在应用程序的整个生命周期中存储按钮按下事件。
fb1 = (Button) findViewById(R.id.button1);
fb1.setBackgroundResource(R.drawable.not_pressed);
fb1.setOnClickListener(new OnClickListener() {
if (!Constants.isPressed) { //if button is not pressed it is set to white color(initially false)
fb1.setBackgroundResource(R.drawable.not_pressed);
fr1 = 0;
//fb1.setEnabled(false);
//sharedPrefs.edit().putBoolean("locked", fb1.isEnabled()).commit();
} else { //if pressed to black
fb1.setBackgroundResource(R.drawable.pressed);
fr1 = 128;
//fb1.setEnabled(true);
//savePreferences("locked", fb1.isEnabled());
sharedPrefs.edit().putBoolean("locked", fb1.isEnabled()).commit();
}
@Override
public void onClick(View v) {
//isPressed = sharedPrefs.getBoolean("locked", false);
fb1.setEnabled(sharedPrefs.getBoolean("locked", true));
System.out.println("BOOL" + isPressed);
Constants.isPressed = true; //Sets is pressed to true throughout lifecycle of your app.
//Execute other onPressed logic here
}
});
这可能会解决您的问题。
答案 1 :(得分:0)
您可以使用选择器选择要显示的颜色 - 这是使用选择器的示例:
<?xml version="1.0" encoding="utf-8" ?>
<item
android:state_enabled="false"
android:drawable="@drawable/remove_contacts_button_disabled"
/>
<item
android:state_enabled="true"
android:state_pressed="true"
android:drawable="@drawable/remove_contacts_button_highlighted"
/>
<item
android:drawable="@drawable/remove_contacts_button_regular"
/>
在onClikLisitner中保存共享首选项,点击即可。