Android Toggle Button Tutorial

Toggle Button concept same as on/off. In Wi-Fi section when press on, your Wi-Fi on and when you press again then Wi-Fi goes switch off.

Step 1.

Create new application with any name from file menu option.

File → New Project → Application name → select API → Add Blank Activity → Activity Name → finish

Step 2.

In activity_main.xml layout file design your application.

Add following Controls:-

toggle button tutorial

Step 3.

Import Package and write following coding in MainActivity.java class file.

	
   import android.view.View;
   import android.widget.Button;
   import android.widget.EditText;
   import android.widget.TextView;
   import android.widget.ToggleButton;

  public class MainActivity extends ActionBarActivity {
    Button b1;
    ToggleButton tg;
    EditText et;
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        b1=(Button)findViewById(R.id.button);
        tg=(ToggleButton)findViewById(R.id.toggleButton);
        et=(EditText)findViewById(R.id.editText);
        tv=(TextView)findViewById(R.id.textView);
        tg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(tg.isChecked())
                {
                    tv.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                else
                {
                    tv.setInputType(InputType.TYPE_CLASS_TEXT);
                }
                
            }
        });
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
                String str=et.getText().toString();
                tv.setText(str);
                if(str.contentEquals("Left"))
                {
                    //change position of text
                    tv.setGravity(Gravity.LEFT);
                    tv.setTextColor(Color.GREEN);
                    tv.setBackgroundColor(Color.LTGRAY);
                }
                else if(str.contentEquals("right"))
                {
                    tv.setGravity(Gravity.RIGHT);
                    tv.setTextColor(Color.BLACK);
                    tv.setBackgroundColor(Color.GREEN);
                }
                else
                {
                    tv.setGravity(Gravity.CENTER);
                    tv.setTextColor(Color.YELLOW);
                    tv.setBackgroundColor(Color.CYAN);
                }
                
            }
        });
    }
    

Step 5. Final Output

Run your application and click on Toggle Button. See the working of application.

toggle button tutorial

Post Your Comment