根据用户的选择更改背景图片

时间:2012-07-20 09:32:46

标签: android android-layout android-image

伙计我希望用户在用户选择时更改我的应用中所有活动的背景图像。 我能够从更改图像的位置更改Activity的背景图像 但如果我尝试更改其他Activity的图像,我会得到NullPointerException! 是的,我已经检查了其他活动的Layout的ID! 这是代码。

public class setting extends Activity {
    TextView tv;
    CheckBox cbS, theme1, theme2;
    RelativeLayout rel;
    OnClickListener checkBoxListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);

        cbS = (CheckBox) findViewById(R.id.cb);
        theme1 = (CheckBox) findViewById(R.id.theme1);
        theme2 = (CheckBox) findViewById(R.id.theme2);
        // cbW=(CheckBox)findViewById(R.id.cbWordPress);
        checkBoxListener = new OnClickListener() {

            public void onClick(View v) {
                if (cbS.isChecked()) {
                    // anything
                }

                if (theme2.isChecked()) {
                    RelativeLayout rel = (RelativeLayout) findViewById(R.id.rel);
                    Resources res = getResources();
                    Drawable drawable = res.getDrawable(R.drawable.back_image1);
                    rel.setBackgroundDrawable(drawable);
                    // findViewById(R.id.rel).setBackgroundResource(R.drawable.back_image1);
                }

            }
        };

        cbS.setOnClickListener(checkBoxListener);
        theme2.setOnClickListener(checkBoxListener);
        // cbW.setOnClickListener(checkBoxListener);

    }
}

2 个答案:

答案 0 :(得分:1)

您无法访问尚未实例化的UI组件。使用Intents跨活动(用户选择,或某些自定义标志或字符串)传递信息,并在已启动的活动中使用此“额外”信息来相应地更改背景。

详细了解文档中的意图,以便更好地理解和举例。

答案 1 :(得分:0)

你不能这样做..当你使用findViewById()引用布局文件时,android系统只会在你当前的ContentView中查找它。 (即您使用setContentView()为当前活动设置的视图)。因此,如果很明显,系统将无法找到您指定的资源,因此您将只获得NullPointerExeption。

您必须单独维护对背景的引用,并在实际传递时在其他Activity中使用它。