我有一个带有src的ImageView,我想让它改变它的src onClick。这很简单,但我想在用户再次点击imageview时将其更改为正常状态。我怎样才能在java中创建它?
修改
我已经尝试过了:
public void act1 (View view) {
ImageView ic1 = (ImageView) findViewById(R.id.id1);
Drawable oldBg = ic1.getBackground();
String oldBgStr = ic1.getBackground().toString();
Drawable ic1light = this.getResources().getDrawable(R.drawable.ic1);
Drawable ic1dark = this.getResources().getDrawable(R.drawable.ic1dark);
ic1.setTag(R.drawable.ic1);
if (oldBg == ic1light){
ic1.setBackground(ic1dark);
}
if (oldBg == ic1dark) {
ic1.setBackground(ic1light);
}
ic1.setImageResource(R.drawable.ic1dark);
}
以下是ImageView和布局的XML:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:background="@color/red"
>
<ImageView
android:id="@+id/id1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="act1"
android:background="@drawable/ic1"
android:adjustViewBounds="true"/>
答案 0 :(得分:3)
只需设置一个布尔值,并在用户点击图片时切换它。每次检查布尔值并显示相应的图像。
private boolean mClicked = false;
public void act1 (View view) {
if(mClicked) {
ic1.setBackground(ic1dark);
}
else {
ic1.setBackground(ic1light);
}
mClicked = !mClicked;
}
答案 1 :(得分:1)
使用布尔值在当前图像集的状态之间切换,如下所示:
private boolean currentState = false;
public void act1 (View view) {
ImageView ic1 = (ImageView) findViewById(R.id.id1);
// set current src
Drawable oldBg = ic1.getBackground();
String oldBgStr = ic1.getBackground().toString();
Drawable ic1light = this.getResources().getDrawable(R.drawable.ic1);
Drawable ic1dark = this.getResources().getDrawable(R.drawable.ic1dark);
ic1.setTag(R.drawable.ic1);
// when this is called from click event of anything else
if(currentState){
ic1.setBackground(ic1light);
currentState = true;
return;
}
if(!currentState){
ic1.setBackground(ic1dark);
currentState = false;
return;
}
}