Write a Program to create 2 toggle button, 1 button and on the of click of the button it should display the state of the both Toggle button
XML Code:
<?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=".Main18Activity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#2196F3"
android:layout_marginTop="200dp">
<ToggleButton
android:id="@+id/tb1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ToggleButton"
android:textOn="On"
android:textOff="Off"
android:textSize="20dp"/>
<ToggleButton
android:id="@+id/tb2"
android:layout_width="50dp" android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ToggleButton"
android:textOn="On"
android:textOff="Off" android:textSize="20dp"/></LinearLayout>
<Button
android:id="@+id/b"
android:background="#000" android:textColor="@color/colorwhite" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change State" android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:textSize="20dp"/>
</LinearLayout>
Java code:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Main18Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main18);
final ToggleButton t1= findViewById(R.id.tb1);
final ToggleButton t2= findViewById(R.id.tb2);
Button b=findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Main18Activity.this,"State of ToggleButton 1:- "+t1.getText()+"\nState of toggle button 2:- "+t2.getText(),Toast.LENGTH_SHORT).show();
}
});
}
}
Output:
Comments
Post a Comment