Friday, 18 January 2013

ToggleButton

Main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF4000"
   
     >

    <ToggleButton
             android:id="@+id/togbtngame"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"            
              android:layout_centerVertical="true"
              android:layout_centerHorizontal="true"
             android:textOn=""
             android:textOff=""                                     
             android:background="@drawable/selector" />
            
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:id="@+id/text"
        android:layout_below="@id/togbtngame"
        android:layout_centerHorizontal="true"
        android:textSize="25dp"
        android:layout_marginTop="20dp"
        android:textColor="#000000"
        />

</RelativeLayout>
Selector.xml(InDrawable)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/on" android:state_checked="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/on" android:state_checked="true" android:state_focused="false"/>
    <item android:drawable="@drawable/off" android:state_checked="false" android:state_pressed="true"/>
    <item android:drawable="@drawable/off" android:state_checked="false" android:state_focused="false"/>

</selector>
MainActivity.java
package com.shekhar;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
   ToggleButton tb;
   TextView tx;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      tb=(ToggleButton)findViewById(R.id.togbtngame);
      tx=(TextView)findViewById(R.id.text);
      tb.setOnClickListener(new OnClickListener() {
       
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(tb.isChecked()){
                tx.setText("ON");
            }
            else{
                tx.setText("OFF");
            }
        }
    });
    }

   
}
OutPut...

No comments:

Post a Comment