我想使用AlertDialog更改活动的背景颜色。这就是我所做的:
private SharedPreferences prefs;
private static final String SELECTED_ITEM = "SelectedItem";
private Editor sharedPrefEditor;
btnchangeColor = (ImageButton) findViewById(R.id.btnchangeColor);
btnchangeColor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CharSequence[] items={"Red","Green","Blue", "Yellow", "#EE82EE"};
AlertDialog.Builder builder = new AlertDialog.Builder(
ContentView_2.this);
builder.setTitle("Pick a Color");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}
});
builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
wvContent = (WebView) findViewById(R.id.wvContent);
//LinearLayout ll=(LinearLayout)findViewById(R.id.wvContent);
if("Red".equals(items[which]))
{
wvContent.setBackgroundColor(Color.RED);
}
else if("Green".equals(items[which]))
{
wvContent.setBackgroundColor(Color.GREEN);
}
else if("Blue".equals(items[which]))
{
wvContent.setBackgroundColor(Color.BLUE);
}
else if("Yellow".equals(items[which]))
{
wvContent.setBackgroundColor(Color.YELLOW);
}
else if("#EE82EE".equals(items[which]))
{
wvContent.setBackgroundColor(Color.rgb(184,184,184));
}
saveSelectedItem(which);
}
});
builder.show();
}});
}
private int getSelectedItem() {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
return prefs.getInt(SELECTED_ITEM, -1);
}
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
}
我还将此代码添加到OnCreate
:
wvContent = (WebView) findViewById(R.id.wvContent);
wvContent.setBackgroundColor(getSelectedItem());
选择颜色并且Web视图(wvContent
)更改为所选颜色,但这不会保存到共享首选项和/或从共享首选项加载。重新启动活动时,它将恢复为默认颜色。
所以问题是:如何正确地将所选颜色保存到SharedPreferences并在活动重新启动时加载它?
非常感谢您的帮助。
答案 0 :(得分:3)
目前,您要在SharedPreferences
中保存所选项目的位置而不是颜色代码。这样做:
wvContent = (WebView) findViewById(R.id.wvContent);
int bg_color=Color.TRANSPARENT;
if("Red".equals(items[which]))
{
wvContent.setBackgroundColor(Color.RED);
bg_color=Color.RED;
}
else if("Green".equals(items[which]))
{
wvContent.setBackgroundColor(Color.GREEN);
bg_color=Color.GREEN;
}
........
// save color in SharedPreferences
saveSelectedItem(bg_color);
现在getSelectedItem()
方法返回先前从微调器中选择的值的颜色代码。