C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Android ToggleButton ExampleAndroid Toggle Button can be used to display checked/unchecked (On/Off) state on the button. It is beneficial if user have to change the setting between two states. It can be used to On/Off Sound, Wifi, Bluetooth etc. Since Android 4.0, there is another type of toggle button called switch that provides slider control. Android ToggleButton and Switch both are the subclasses of CompoundButton class. Android ToggleButton classToggleButton class provides the facility of creating the toggle button. XML Attributes of ToggleButton classThe 3 XML attributes of ToggleButton class.
Methods of ToggleButton classThe widely used methods of ToggleButton class are given below.
Android ToggleButton Exampleactivity_main.xmlDrag two toggle button and one button for the layout. Now the activity_main.xml file will look like this: File: activity_main.xml
Activity classLet's write the code to check which toggle button is ON/OFF. File: MainActivity.java
package example.TheDeveloperBlog.com.togglebutton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { private ToggleButton toggleButton1, toggleButton2; private Button buttonSubmit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addListenerOnButtonClick(); } public void addListenerOnButtonClick(){ //Getting the ToggleButton and Button instance from the layout xml file toggleButton1=(ToggleButton)findViewById(R.id.toggleButton); toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2); buttonSubmit=(Button)findViewById(R.id.button); //Performing action on button click buttonSubmit.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { StringBuilder result = new StringBuilder(); result.append("ToggleButton1 : ").append(toggleButton1.getText()); result.append("\nToggleButton2 : ").append(toggleButton2.getText()); //Displaying the message in toast Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show(); } }); } } Output:
Next TopicAndroid Checkbox Example
|