Develop an application to create a toggle button to display ON / OFF Bluetooth on the display screen
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity"
android:padding="20dp">
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="ToggleButton"
android:textOn="ON"
android:textOff="OFF"
android:textSize="20sp"
android:layout_centerInParent="true"/>
<TextView android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/toggleButton"
android:text="Bluetooth is OFF"
android:gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textSize="20sp"
android:textColor="@color/colorAccent"/>
</RelativeLayout>
MainActivity.java
package com.example.togglebuttonbluetooth;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
ToggleButton toggleButton;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = findViewById(R.id.toggleButton);
textView = findViewById(R.id.textView);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
textView.setText("Bluetooth is " + toggleButton.getTextOn());
}
else
{
textView.setText("Bluetooth is " + toggleButton.getTextOff());
}
}
});
}
}
OUTPUT