1

I am having a button I want to do toggle on button like on and off,What I required is I am having two backgroundimages.

When I first time tap on button first background image should be done and on second time second background image should be changed like in toggle button.

Anybody please help me as I am new to android.

This is my activity:

public class MainActivity extends Activity {

    private Button Button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button1 = (Button) findViewById(R.id.Button1);
        Button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                v.setBackgroundResource(R.drawable.ic_launcher);

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}  

Thanks.

4 Answers4

1

Create a xml file in the drawable with the following code and change the background of the button to this drawable

customButton.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="false" android:drawable="@drawable/image_not_pressed">      </item>
    <item android:state_pressed="true" android:drawable="@drawable/image_pressed"></item>
</selector>

Then add background to the image

<ImageView
    android:layoutWidth="wrap_content"
    android:layoutWidth="wrap_content"
    android:background="@drawable/customButtom" />
SathMK
  • 1,171
  • 1
  • 8
  • 18
0

You can maintain the setSelected state for the Button and change the image by checking if it isSelected on Button click

Try using

Button button = new Button(this);

        button.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                if (v.isSelected())
                {
                  v.setSelected(false);
                }
                else
                {
                  v.setSelected(true);
                }
            }
        });

Let me know if this works.

Apoorv
  • 13,470
  • 4
  • 27
  • 33
0

You can use setTag to do that.

First>

Button1.setTag("ON");

and secondly in your onclicklistener add this:

if (v.getTag().toString().equals("ON")) {
            v.setTag("OFF");
             v.setBackgroundResource(R.drawable.ic_launcher);
        }else {
            v.setTag("ON");
             v.setBackgroundResource(R.drawable.ic_launcher2);
        }
invisbo
  • 3,399
  • 1
  • 16
  • 20
0

Use ImageButton instead of Button,change image on the surface of the ImageButton by the setImageResource(int) method.

LL520
  • 159
  • 3