Reputation: 25
So I have several buttons, and I want the background of an app screen to change depending on which button I click. So if I click a button with the writing "blue", the background changes to a specified image which I've created in the res folder. Thanks in advance.
Upvotes: 1
Views: 3260
Reputation: 24181
in your onCreate()
Method get your Views
like this :
rootLayout = (LinearLayout) findViewById(R.id.rootLayout);
btnBlue = (Button) findViewById(R.id.btnBlue);
btnRed = (Button) findViewById(R.id.btnRed);
btnGreen = (Button) findViewById(R.id.btnGreen);
and set the onClickListener
on all buttons like this :
btnRed.setOnClickListener(this);
btnGreen.setOnClickListener(this);
btnBlue.setOnClickListener(this);
and override the method onClick()
like this :
@Override
public void onClick(View v){
Drawable background = null;
switch(v.getId()){
case R.id.btnBlue :drawable = getResources().getDrawable(R.drawable.imageBlue); break;
case R.id.btnRed : drawable = getResources().getDrawable(R.drawable.imageRed); break;
case R.id.btnGreen : drawable = getResources().getDrawable(R.drawable.imageGreen); break;
}
rootLayout.setBackgroundDrawable(background);
}
Upvotes: 3
Reputation: 400
To change image by using code
public void onClick(View v) {
if(v==ButtonName)
ButtonName.setImageResource(R.drawable.ImageName);
}
or using XML file
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/login_selected" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
<item android:drawable="@drawable/login" /> <!-- default -->
OnClick just add this code
ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName))
Even if you want me background drawable, here it is:
android:background="@drawable/ImageName"
Now, you can compound them
Upvotes: 2