Thursday, 6 February 2020

How to set switch button or toggle button in android

In Android toggle button was deprecated. now android widget used switch
instead of toggle.

I suggest you to use switch instead of toggle button.
both working are same and only change is looking like material design.


In Layout :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
              android:layout_width="match_parent"  
              android:layout_height="match_parent"  
              android:layout_gravity="center"  
              android:gravity="center"  
              android:orientation="vertical">

    <Switch      
          android:id="@+id/simpleSwitch"      
          android:layout_width="wrap_content"      
          android:layout_height="wrap_content"      
          android:checked="false"      
          android:text="Sound " />

</LinearLayout>





and in java  :

//just declare switch widget by using find view by id

Switch aSwitch=findViewById(R.id.simpleSwitch);

//below all are switch widget listener use according to the nature of
//user activity
aSwitch.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
    }
});

aSwitch.setOnCheckedChangeListener(
     new CompoundButton.OnCheckedChangeListener() {
    @Override  
    public void onCheckedChanged(CompoundButton buttonView,
             boolean isChecked) {
        Toast.makeText(context, "Hello button is "+
                             isChecked, Toast.LENGTH_SHORT).show();
    }
});

aSwitch.setOnDragListener(new View.OnDragListener() {
    @Override    public boolean onDrag(View v, DragEvent event) {
        return false;
    }
});

aSwitch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override  
    public void onFocusChange(View v, boolean hasFocus) {
  
    }
});





below image switch uncheck





below image show switch is checked




Thanks

No comments:

Post a Comment