I am trying to show toast with the color name of the CheckBox that selected, but when I click on the button, nothing happens, I tried to use the LinearLayout as a parent of all views to get the id of the chosen Checkbox, first I tried to create it as a Linearlayout in main activity but the app is stopped when I choose one checkbox and click on the button, then I changed it to a View and cast it to LinearLayout
here's my code
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = (LinearLayout)findViewById(R.id.view);
Button btn = findViewById(R.id.button1);
CheckBox chk1 = findViewById(R.id.chk1);
CheckBox chk2 = findViewById(R.id.chk2);
CheckBox chk3 = findViewById(R.id.chk3);
btn.setOnClickListener(v -> {
switch (view.getId()) {
case R.id.chk1:
if (chk1.isChecked())
Toast.makeText(MainActivity.this, "Green", Toast.LENGTH_LONG).show();
break;
case R.id.chk2:
if (chk2.isChecked())
Toast.makeText(MainActivity.this, "Orange", Toast.LENGTH_LONG).show();
break;
case R.id.chk3:
if (chk3.isChecked())
Toast.makeText(MainActivity.this, "Orange", Toast.LENGTH_LONG).show();
break;
default:
}
});
}
The layout
<?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"
android:id="@+id/view"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_gravity="center"
android:text="@string/app_name"
android:textColor="@color/black"
android:textAlignment="center"
android:textSize="24sp"
/>
<CheckBox
android:id="@+id/chk1"
android:text="Green"
android:textSize="33sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</CheckBox>
<CheckBox
android:id="@+id/chk2"
android:text="Orange"
android:textSize="33sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</CheckBox>
<CheckBox
android:id="@+id/chk3"
android:text="Blue"
android:textSize="33sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</CheckBox>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_gravity="center"
android:text="@string/button1"
android:textAllCaps="false"
android:textSize="24sp"
>
</Button>
</LinearLayout>