This may be a silly question, but I am struck halfway when I tried to create a simple app with a checkbox. When I use the checkbox to show and hide a single text, this works fine. But if it's for a second text, the app crashes. I wanted to hide one text and show another when the checkbox is clicked.
Here is the full code:
MainActivity.Java
package ***
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView txtHelloWorld;
private TextView txtHelloWorldChecked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox checkBoxVisibility = findViewById(R.id.checkBox_visibility);
txtHelloWorld = findViewById(R.id.txtHelloWorld);
boolean isChecked = checkBoxVisibility.isChecked();
updateTextVisibility(isChecked);
checkBoxVisibility.setOnClickListener(v -> {
boolean isChecked1 = ((CheckBox)v).isChecked();
updateTextVisibility(isChecked1);
});
}
private void updateTextVisibility(boolean isChecked) {
if (isChecked) {
txtHelloWorld.setVisibility(View.VISIBLE);
txtHelloWorldChecked.setVisibility(View.INVISIBLE);
} else {
txtHelloWorld.setVisibility(View.INVISIBLE);
txtHelloWorldChecked.setVisibility(View.VISIBLE);
}
}
}