Friday 22 July 2016

Switch Example

Screenshots :




activity_main.xml :



<?xml version="1.0" encoding="utf-8"?>
<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="com.chantisandroid.switchexample.MainActivity">

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/textView"
        android:layout_below="@+id/switch1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="77dp" />
</RelativeLayout>



MainActivity.java :


package com.chantisandroid.switchexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    Switch switch1;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textView);
        switch1 = (Switch)findViewById(R.id.switch1);

        switch1.setOnCheckedChangeListener(this);

    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if(switch1.isChecked()){
            textView.setText("Swich On");
        }else{
            textView.setText("Swich Off");
        }
    }
}


No comments:

Post a Comment

Alarm Manager Example in Android