Thursday, March 1, 2012

Android toggle button example

This program is for accessing data from toggle button

Step 1) Put below code in your main java file


package toggle.button;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class Toggle_buttonActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final TextView tv=(TextView)findViewById(R.id.textView1);
        final ToggleButton tb=(ToggleButton)findViewById(R.id.toggleButton1);
       
        tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                                               
                                                public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                                                                // TODO Auto-generated method stub
                                                                tv.setText(tb.getText());
                                                                                                                                                               
                                                }
                                });
     }
}



Step 2)Code for your main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
   
<ToggleButton
android:text="ToggleButton"
android:id="@+id/toggleButton1"
 android:layout_width="wrap_content"
  android:layout_height="wrap_content">
</ToggleButton>
<TextView
android:text="TextView"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>

</LinearLayout>

No comments:

Post a Comment