我已经能够更改活动背景的颜色(请参见此帖子)。现在,一个要求是对背景图像进行相同的处理。我的意思是,我可以点击一个按钮,选择一个选项,并将当前Activity的背景图像更改为新的背景图像。
这是我所做的:
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={getString(R.string.default),getString(R.string.pix1), getString(R.string.pix2))};
AlertDialog.Builder builder = new AlertDialog.Builder(
ContentView.this);
builder.setTitle((getResources().getString(R.string.color_switch)));
builder.setPositiveButton((R.string.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) {
wvContent = (WebView) findViewById(R.id.wvContent);
int bg_color=0;
if(getString(R.string.default).equals(items[which]))
{
wvContent.setBackgroundColor(0);
BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.default);
bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
wvContent.setBackgroundDrawable(bg);
bg_color=R.drawable.default;
}
else if(getString(R.string.pix1).equals(items[which]))
{
wvContent.setBackgroundColor(0);
BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.pix1);
bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
wvContent.setBackgroundDrawable(bg);
bg_color=R.drawable.pix1;
}
else if(getString(R.string.pix2).equals(items[which]))
{
wvContent.setBackgroundColor(0);
BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.pix2);
bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
wvContent.setBackgroundDrawable(bg);
bg_color=R.drawable.pix2;
}
saveSelectedItem(bg_color);
}
});
builder.show();
使用以下代码保存和加载更改:
//OnCreate
wvContent = (WebView) findViewById(R.id.wvContent);
wvContent.setBackgroundColor(getSelectedItem());
...
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();
}
当从对话框列表中选择活动背景图像时,该图像确实会更改,但更改不会保存并在下次重新启动活动时加载。
我现在不知道如何解决这个问题。您能帮忙吗?非常感谢。