Android:使背景图片可更改

时间:2012-06-05 11:46:01

标签: android android-layout

我有一个带有背景图片的Android应用程序。我的目标是创建3或4个背景图像,并为用户提供更改背景的可能性。

实际上,我有4张名为bg1.png,bg2.png,bg3.png和bg4.png的图片。 我想到了在Strings.xml中使用图像名称声明字符串值“background”的内容。背景图像的名称将始终从背景字符串中获取,当用户更改背景时,这将仅更改字符串背景的值。

这个想法是好的还是有更简单的东西? 如何使用“background”字符串的值在xml布局文件中设置布局的背景?我是以编程方式执行此操作的吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

我认为如果你想将背景更改为活动布局,可以使用布局的setBackground方法来做到这一点:

activityLayout = (LinearLayout)findViewById(R.id.tableLayout1);
activityLayout.setBackgroundDrawable(getResources().getDrawable(R.id.somedrawable))

您可以使用例如SharedPreference存储背景图像,然后在启动活动时读取包含背景的首选项。例如,当用户选择背景时:

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefEditor.putInt("backgroudResourceId", userchoice);
prefEditor.commit();

当活动开始时,您必须从SharedPreference中读取resourceId:

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
drawableid = myPrefs.getInt("backgroundResourceId", defaultvalue); 
yourlayout.setBackground(drawableid);

其中,如果未设置首选项,则defaultvalue是默认值。应该初始化yourLayout(以与活动布局相同的方式)。