Tuesday, March 4, 2014

Android : Implement an Image as Toggle button

 Implement an Image as Toggle button




Step 1 .


Step 2  : activity_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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@drawable/backg">

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="105dp"
    android:background="@drawable/off"
    android:button="@drawable/button_xml"
    android:minHeight="1dip"
    android:minWidth="2dip"
    android:textOff=" "
    android:textOn=" " />

</RelativeLayout>


Step 3 : MainActivity.java

public class MainActivity extends Activity {
public String result ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        final ToggleButton  tb = (ToggleButton) findViewById(R.id.toggleButton1);
         tb.setOnClickListener(new OnClickListener() {
             public void onClick(View v)
             {
                 String s;
                 if(tb.isChecked())
                     
                 {
                     s="ON";
                     Toast.makeText(getBaseContext(),"Button is ON",Toast.LENGTH_SHORT).show();         
                 }
                 else
                 {
                     s="OFF";
                     Toast.makeText(getBaseContext(),"Button is OFF",Toast.LENGTH_SHORT).show();
                     }
                 
                         }
         });
}
       

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

No comments:

Post a Comment