You are on page 1of 3

Practical No: 9

 Develop a program to implement Button, Image Button and Toggle


Button.

 activity_main.xml

<?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"
android:orientation="vertical"
android:background="#3EB489"
tools:context=".MainActivity">
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity"
android:background="#3EB489"

android:id="@+id/background">

<ToggleButton
android:id="@+id/switch_onoff"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="off"
android:textSize="50sp"
android:textStyle="bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="50dp"
android:switchMinWidth="80dp"
/>

<ImageView
android:id="@+id/img_bulb"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/switch_onoff"
android:layout_marginTop="50dp"
>

</ImageView>
</androidx.constraintlayout.widget.ConstraintLayout>
 MainActivity.java
package com.example.pr9;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.widget.CompoundButton;

import com.example.pr9.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {


ActivityMainBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding=ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
set_image_resource(false);

binding.switchOnoff.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonview, boolean
ischecked) {
set_image_resource(ischecked);
}
});
}
public void set_image_resource(boolean condition)
{
if(condition)
{
binding.imgBulb.setImageResource(R.drawable.bulb_on);
binding.switchOnoff.setText("on");
binding.background.setBackgroundColor(Color.GRAY);
}
else
{
binding.imgBulb.setImageResource(R.drawable.bulb_off);
binding.switchOnoff.setText("off");
binding.background.setBackgroundColor(Color.DKGRAY);
}
}
}
 Output:

You might also like