Android: How to create slide (on/off) button

六月ゝ 毕业季﹏ 提交于 2019-11-28 06:59:57

//in your layout design the below line

<RelativeLayout android:layout_width="wrap_content" android:id="@+id/rl_onoff"
    android:layout_height="wrap_content">
<ImageView android:id="@+id/on_btn" android:layout_width="80dp"  android:layout_height="40dp" android:src="@drawable/on_btn" android:visibility="visible"></ImageView>
<ImageView android:id="@+id/off_btn" android:layout_width="80dp"  android:layout_height="40dp" android:src="@drawable/off_btn" android:visibility="invisible"></ImageView>
   </RelativeLayout>

// in your activity call this

ImageView mNotification_on_btn=(ImageView)findViewById(R.id.on_btn);
ImageView mNotification_off_btn=(ImageView)findViewById(R.id.off_btn);

    mNotification_on_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mNotification_on_btn.setVisibility(View.GONE);
                mNotification_off_btn.setVisibility(View.VISIBLE);
            }
        });
    mNotification_off_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mNotification_off_btn.setVisibility(View.GONE);
                mNotification_on_btn.setVisibility(View.VISIBLE);
            }
        });

// this will switch like iphone style on off toggle button

obrien

Well it seems that Switch component is the best solution if your target SDK is higher than 4.0 (Ice Cream Sandwich). So for the others who will face the same problem look at it. :)

Manikandan

You can achieve this by use check box or ToggleButton. Below is an example

xml file

 <CheckBox
        android:id="@+id/check_on_of"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/chec_box_on_off"
       />

drawable chec_box_on_off file is

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/check_box_on" android:state_checked="true"/>
<item android:drawable="@drawable/check_box_off" android:state_checked="false"/>
</selector>

you will get like on off button and also you can check whether checkbox is on or off.

the java code is

 CheckBox check = (CheckBox)findViewById(R.id.check_on_of);
 check.isChecked();

Similarly, you can also achieve this using ToggleButton.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!