Translate

Sunday, April 7, 2019

Android | Working With Checkbox



1. 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"
tools:context=".MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hobby:"
android:textSize="30sp"
android:textStyle="bold" />

<CheckBox
android:id="@+id/chkreading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Reading"
android:textSize="20sp"
android:textStyle="bold" />

<CheckBox
android:id="@+id/chkwriting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Writing"
android:textSize="20sp"
android:textStyle="bold" />

<CheckBox
android:id="@+id/chkgaming"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Gaming"
android:textSize="20sp"
android:textStyle="bold" />

</LinearLayout>


1. MainActivity.java

package com.example.yt_checkbox;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

CheckBox chkreading, chrwriting, chkgaming;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

chkreading = findViewById(R.id.chkreading);
chrwriting = findViewById(R.id.chkwriting);
chkgaming = findViewById(R.id.chkgaming);

chkreading.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkreading.isChecked()) {
Toast.makeText(MainActivity.this, "Reading", Toast.LENGTH_SHORT).show();
}
}
});

chrwriting.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chrwriting.isChecked()) {
Toast.makeText(MainActivity.this, "Writing", Toast.LENGTH_SHORT).show();
}
}
});

chkgaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkgaming.isChecked()) {
Toast.makeText(MainActivity.this, "Gaming", Toast.LENGTH_SHORT).show();
}
}
});
}
}


Click here to download source code

No comments:

Post a Comment