I have an image button as a on/off button, i want to change the source image of it upon clicking to switch between on and off, all i have to do is to place a comparison in my click listener and a switch operation, the switch goes fine, the problem here is with the comparison, i tried like million ways and all didn't work,
for example i tried:
public void onClick(View v) {
if (v == power) {
Drawable fDraw = power.getBackground();
Drawable sDraw = getResources().getDrawable(R.drawable.acoffdormant);
Bitmap bitmap = ((BitmapDrawable)fDraw).getBitmap();
Bitmap bitmap2 = ((BitmapDrawable)sDraw).getBitmap();
if (bitmap == bitmap2) {
power.invalidateDrawable(getResources().getDrawable(R.drawable.acoffdormant));
power.setImageResource(R.drawable.acondormant);
} else {
power.invalidateDrawable(getResources().getDrawable(R.drawable.acondormant));
power.setImageResource(R.drawable.acoffdormant);
}
}
}
};
And also:
if (getResources().getDrawable(R.drawable.acoffdormant).hashCode() == power.getBackground().hashCode())
And Also:
v.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.acoffdormant).getConstantState())
And Also :
Drawable state = power.getBackground();
Bitmap statebit = ((BitmapDrawable)state).getBitmap();
Bitmap off = BitmapFactory.decodeResource(power.getResources(),
R.drawable.acoffdormant);
if (statebit == off) {
power.invalidateDrawable(getResources().getDrawable(R.drawable.acoffdormant));
power.setImageResource(R.drawable.acondormant);
} else {
power.invalidateDrawable(getResources().getDrawable(R.drawable.acondormant));
power.setImageResource(R.drawable.ac_fan);
}
And Also:
if (power.getBackground().getConstantState().equals
(getResources().getDrawable(R.drawable.acoffdormant).getConstantState()))
And my XML :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
android:background="@android:color/transparent"
android:text="@string/power"
android:textColor="#00CCCC"
android:textSize="20dp"
android:textStyle="bold" />
<ImageButton
android:id="@+id/power"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:clickable="true"
android:adjustViewBounds="true"
android:background="@android:color/transparent"
android:scaleType="centerInside"
android:src="@drawable/acoffdormant" />
</LinearLayout>