改变android背景方法,java – 如何以编程方式更改Android Activity的背景图像

我能够改变活动背景的颜色(见

this post).现在要求对背景图像做同样的事情.我的意思是我可以单击一个按钮,选择一个选项并将当前活动背景图像更改为新的.

这是我做的:

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();

}

从对话框列表中选择活动背景图像时会发生更改,但下次重新启动活动时不会保存和加载更改.

我现在不知道如何解决这个问题.你能帮忙吗?非常感谢.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值