切换按钮使用两个图像在不同的状态

我需要使用两个图像而不是 ON/OFF 状态的切换按钮。

在关闭状态下,我设置了一个背景图像,但是当我使用背景图像时,关闭文本无法删除。

我不能设置另一个图像的 ON 状态,通过点击切换按钮: ( 我是机器人新手。 我希望你们能帮我解决这个问题

110897 次浏览

Do this:

<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/check"   <!--check.xml-->
android:layout_margin="10dp"
android:textOn=""
android:textOff=""
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_centerVertical="true"/>

create check.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>


</selector>

AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:

<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/check"   //check.xml
android:background="@null"/>

check.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>

You can try something like this. Here on click of image button I toggle the imageview.

holder.imgitem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(!onclick){
mSparseBooleanArray.put((Integer) view.getTag(), true);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
onclick=true;}
else if(onclick)
{
mSparseBooleanArray.put((Integer) view.getTag(), false);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);


onclick=false;
}
}
});