Change background image on user's choice

自古美人都是妖i 提交于 2020-01-17 04:08:07

问题


Guys I want the user to change the background image of all the activities in my app on user selection. I am able to change the background image of the Activity from where am changing the image but if I try to change the image of other Activity, I get a NullPointerException! Yes, I have checked that the id of other activity's Layout ! this is the code.

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

    }
}

回答1:


You cannot do this.. When you refer a layout file using findViewById(), the android system looks for this in your current ContentView only. (i.e the view which you have set using setContentView() for the current activity). So obvioulsy the sytem will not be able find the resource you are specifying and hence you will get the NullPointerExeption only.

You have to maintain the reference to the backgrounds separately and use it in your other Activity when you actually pass on there.




回答2:


you cannot access the UI components which are not yet instantiated. Use Intents to pass information across activities (user's choice, or some custom flags or Strings) and use this "extra" information in the launched activity to change the background accordingly.

Read more about intents in the documentation for better understanding and examples.



来源:https://stackoverflow.com/questions/11576668/change-background-image-on-users-choice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!