Android 单击更改切换按钮图像
我知道已经有人问过、回答过、回答过了。我两个都试过了,但都不适合我 我有一个favorite按钮,如果按下该按钮,我会在Android 单击更改切换按钮图像,android,android-layout,togglebutton,Android,Android Layout,Togglebutton,我知道已经有人问过、回答过、回答过了。我两个都试过了,但都不适合我 我有一个favorite按钮,如果按下该按钮,我会在数据库中将该项目设置为favorite,并替换切换按钮的图像,反之亦然。我是这样做的: <ToggleButton android:id="@+id/btnFavorite" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn
数据库中将该项目设置为favorite,并替换切换按钮的图像,反之亦然。我是这样做的:
<ToggleButton
android:id="@+id/btnFavorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn=""
android:textOff=""
android:layout_marginRight="5dp"
android:background="@drawable/favorite_btn_style" />
在oncreate
中,我检查项目是否已设置为收藏夹,然后setchecked
设置为true
:
if (movieObj.getIsFav().intValue() == 1) {
btnFav.setChecked(true);
}
下面是按钮上的我的onclicklistener
:
btnFav.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (!btnFav.isChecked()) {
btnFav.setChecked(true);
// set favorite
dbHelper.updateMovieFavorite(movieObj.getId().intValue(), 1);
} else {
btnFav.setChecked(false);
// set favorite
dbHelper.updateMovieFavorite(movieObj.getId().intValue(), 0);
}
}
});
函数被调用,并且执行得很好,但图像没有变化。。我做错了什么?在res/drawable文件夹中创建一个文件按钮\u toggle.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="false"
android:drawable="@drawable/ic_slide_switch_off" />
<item
android:state_checked="true"
android:drawable="@drawable/ic_slide_switch_on" />
</selector>
删除OnClick方法中的btnFav.setChecked(true)
和btnFav.setChecked(false)
。这是一个togglebutton,它可以通过每次单击自行切换设置并将其重置为旧值。因此,在您的情况下,它始终具有相同的值(起始值)。
我建议您使用setOnCheckedChangeListener
而不是onClickListener
尝试使用android:button=“@drawable/favorite\u btn\u style”和android:background=“@android:color/transparent”组合。要自定义复选框、单选框和切换按钮,您应该使用android:button而不是android:background
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="false"
android:drawable="@drawable/ic_slide_switch_off" />
<item
android:state_checked="true"
android:drawable="@drawable/ic_slide_switch_on" />
</selector>