Android toggle button
Hello Droid Guys,
Today ,I am sharing the code of custom toggle button in android. How to make a toggle switch button like
iPhone.
1. Create a new project in Eclipse File New ⇒ Android ⇒ Application Project and fill the required details.
2. Create required files needed to show a toggle switch button. I am using my default activity_main.xml as where I place the toggle button code and created a new xml file inside
drawable in which I change my toggle button on selection.
1. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/btntoggle_selector"
android:textColor="@android:color/transparent"
android:textOff="Off"
android:textOn="On" />
</LinearLayout>
2.btntoggle_selector
1: <?xml version="1.0" encoding="utf-8"?>
2: <selector xmlns:android="http://schemas.android.com/apk/res/android">
3: <item android:drawable="@drawable/on" android:state_checked="true" android:state_pressed="true"/>
4: <item android:drawable="@drawable/on" android:state_checked="true" android:state_focused="false"/>
5: <item android:drawable="@drawable/off" android:state_checked="false" android:state_pressed="true"/>
6: <item android:drawable="@drawable/off" android:state_checked="false" android:state_focused="false"/>
7: </selector>
3.CustomToggleButtonActivity1: package com.mukesh.customtogglebutton;
2: import android.app.Activity;
3: import android.os.Bundle;
4: import android.view.View;
5: import android.view.View.OnClickListener;
6: import android.widget.Toast;
7: import android.widget.ToggleButton;
8: import com.technotalkative.customtogglebutton.R;
9: public class CustomToggleButtonActivity extends Activity {
10: ToggleButton toggleBtn;
11: /** Called when the activity is first created. */
12: @Override
13: public void onCreate(Bundle savedInstanceState) {
14: super.onCreate(savedInstanceState);
15: setContentView(R.layout.main);
16: toggleBtn = (ToggleButton) findViewById(R.id.toggle);
17: toggleBtn.setOnClickListener(new OnClickListener() {
18: public void onClick(View v) {
19: String state = toggleBtn.getText().toString();
20: Toast.makeText(CustomToggleButtonActivity.this,
21: "Toggle State :" + state, Toast.LENGTH_LONG).show();
22: }
23: });
24: }
25: }
You can use default android switches :
Enjoy coding ... :)
You might also like:
Không có nhận xét nào:
Đăng nhận xét