Saturday, January 3, 2015

Switch Example in Android

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"
    tools:context="${packageName}.${activityClass}" >

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="62dp"
        android:text="Switch" />

</RelativeLayout>


MainActivity.java:
package com.ram.switchexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Switch switch1 = (Switch)findViewById(R.id.switch1);
        
        switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
Toast.makeText(getApplicationContext(), "ON", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_LONG).show();
}
}
});
    }
}

Switch Example in Android Rating: 4.5 Diposkan Oleh: Unknown

0 comments:

Post a Comment