Practical No 09
Practical No 09
Practical No 09
activity_main.xml
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;
@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: