PRACTICAL 11
PROGRAM TO IMPLEMENT CHECK BOX
The layout of the MainActivity is defined as follows. activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I Agree to the Terms and Conditions"
android:layout_centerInParent="true"/>
</RelativeLayout>
The MainActivity.java is defined below.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the checkbox view
checkBox = findViewById(R.id.checkBox);
// Set a listener for the checkbox state changes
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(getApplicationContext(), "You have agreed to the terms and conditions",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Please agree to the terms and conditions",
Toast.LENGTH_SHORT).show();
}
}
});
}
}