How To Toggle Background Image On Button Click?
I have this code: button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub button1.setB
Solution 1:
you can take a variable
int i=0;
it will increase with every click.
if(i%2==0)
setone image
elseset another image
Solution 2:
How about creating an array of the drawable's IDs and saving an index:
privatefinalint[] myDrawables = {R.drawable.detailpressed, R.drawable.detailpressed1, ...};
//...
button1.setOnClickListener(newOnClickListener() {
intindex=0;
@OverridepublicvoidonClick(View v) {
button1.setBackgroundResource(myDrawables[index++ % myDrawables.length]);
Chapter_sync.add(chapid);
}
}
Solution 3:
declare variable as
booleanisOddClicked=true;
And update your click listener as
button1.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
// TODO Auto-generated method stub//Do stuff here for chnaging background of buttonif(isOddClicked) {
button1.setBackgroundResource(R.drawable.detailpressed);
isOddClicked = false;
} else {
button1.setBackgroundResource(R.drawable.detailpressed_SECOND_IMAGE);
isOddClicked = true;
}
//Do your taskChapter_sync.add(chapid);
}
NOTE: If your requirement moves between two images then you can use toggle button
and customize it. It will work for same as your requirement.
Solution 4:
if xml as the following
<code><Buttonandroid:id="@+id/btnListView"android:layout_width="35dp"android:layout_height="35dp"android:background="@drawable/list_view"android:onClick="switchToListView"android:visibility="visible"
/><Buttonandroid:id="@+id/btnGridView"android:layout_width="35dp"android:layout_height="35dp"android:background="@drawable/grid_view"android:onClick="switchToGridView"android:visibility="gone"
/><code>
handling Code will be like
<code>
publicvoidswitchToListView(View view) {
(Button) findViewById(R.id.btnListView).setVisibility(View.GONE);
(Button) findViewById(R.id.btnGridView).setVisibility(View.VISIBLE);
}
publicvoidswitchToGridView(View view) {
(Button) findViewById(R.id.btnGridView).setVisibility(View.GONE);
(Button) findViewById(R.id.btnListView).setVisibility(View.VISIBLE);
}
</code>
Post a Comment for "How To Toggle Background Image On Button Click?"