mainActivity.java - code of SwitchButton
package com.example.raghukm.aswitch;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Switch aSwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aSwitch=(Switch)findViewById(R.id.switch1);
}
public void onSwitchClick(View view) {
if(aSwitch.isChecked())
Toast.makeText(getApplicationContext(),"Switch is On",Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(),"Switch is off",Toast.LENGTH_SHORT).show();
}
}
activity_main.xml - code of SwitchButton
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.raghukm.aswitch.MainActivity">
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="62dp"
android:onClick="onSwitchClick"/>
</android.support.constraint.ConstraintLayout>
SHARE THIS
0 Post a Comment: