Changing background image on button click android

2019-07-10 17:01发布

问题:

I am trying to change the background image of an activity on button click, but not being able to do so. Can you guys tell me how can I can do that?

Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try
        {
            Activity activity = Selection.this;
            //Drawable db = Drawable..createFromPath(R.drawable.love1);

            // The below line gives error because setbackgroundImage 
            // is supposed to take a drawable object as an argument. 
            // Now what to do?                                  
            activity.findViewById(android.R.id.content)
            .setBackground(Drawable.createFromPath("res/love1.jpg"));

            // What to do to correct the above line?

            mySong = MediaPlayer.create(Selection.this, R.raw.song1);
            mySong.start();
        }
        catch(Exception ee){
            TextView tv = (TextView) findViewById(R.id.textView1);
            tv.setText(ee.getMessage());
        }
    }
});

I tried with Color.RED using setBackgroundColor but that too is not working. PS: I have not changed anything in the xml file for accomplishing this.

回答1:

I think the easiest way is to use layout in your xml file for your activity.. for example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/linearLayoutID" 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/background_img1" >

and then change it from your Activity when you want e.g. after the button click:

 LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linearLayoutID);
 mLinearLayout.setBackgroundResource(R.drawable.background_img2);


回答2:

Change setBackground(Drawable) to setBackgroundResource(R.drawable.filename)



回答3:

LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.LayoutID); mLinearLayout.setBackgroundResource(R.drawable.image_name);