Android Switch

Android Development

Android Switch :-

⇛ layout > .xml file :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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=".First"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/Idtextview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#c1091e"
android:padding="10dp"/>
<Switch
android:id="@+id/Idswitch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20sp"/>
</LinearLayout>

⇛ java file :

package com.example.dell.aswitch;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
public class First extends AppCompatActivity {
private Switch s1;
private TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
s1 = (Switch) findViewById(R.id.Idswitch1);
txt1 = (TextView) findViewById(R.id.Idtextview1);
/*When click on Switch, the listener will execute*/
s1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (s1.isChecked()){
txt1.setText("Switch is On");
}else {
txt1.setText("Switch is Off");
}
}
});
}
}

No comments

Powered by Blogger.