I have this code:
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
<code>
<Button
android:id="@+id/btnListView"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="@drawable/list_view"
android:onClick="switchToListView"
android:visibility="visible"
/>
<Button
android:id="@+id/btnGridView"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="@drawable/grid_view"
android:onClick="switchToGridView"
android:visibility="gone"
/>
<code>
<code>
public void switchToListView(View view) {
(Button) findViewById(R.id.btnListView).setVisibility(View.GONE);
(Button) findViewById(R.id.btnGridView).setVisibility(View.VISIBLE);
}
public void switchToGridView(View view) {
(Button) findViewById(R.id.btnGridView).setVisibility(View.GONE);
(Button) findViewById(R.id.btnListView).setVisibility(View.VISIBLE);
}
</code>
declare variable as
boolean isOddClicked = true;
And update your click listener as
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Do stuff here for chnaging background of button
if(isOddClicked) {
button1.setBackgroundResource(R.drawable.detailpressed);
isOddClicked = false;
} else {
button1.setBackgroundResource(R.drawable.detailpressed_SECOND_IMAGE);
isOddClicked = true;
}
//Do your task
Chapter_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.
How about creating an array of the drawable's IDs and saving an index:
private final int[] myDrawables = {R.drawable.detailpressed, R.drawable.detailpressed1, ...};
//...
button1.setOnClickListener(new OnClickListener() {
int index = 0;
@Override
public void onClick(View v) {
button1.setBackgroundResource(myDrawables[index++ % myDrawables.length]);
Chapter_sync.add(chapid);
}
}
you can take a variable
int i=0;
it will increase with every click.
if(i%2==0)
set one image
else
set another image