• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Checkbox to show/hide textview

little_star

Lurker
Jul 17, 2021
1
0
Hi,
I am trying to create a small app as part of my learning experience in Android.
I got this code to show and hide a text using a checkbox
How can I control 2 different text with one checkbox (show one text and hide another and vice-versa)
Can someone please help me to make this work

Code:
Import ...
public class MainActivity extends AppCompatActivity {

    private TextView txtHelloWorld;

   @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);
        } else {
            txtHelloWorld.setVisibility(View.INVISIBLE);
        }
    }
}
 
Hi little_star,

1) If you need to create one or more texts to show/hide, you will need a corresponding number of TextViews

private TextView txtHelloWorld, txtAnotherText;

2) Now you need the corresponding layout references

txtHelloWorld = findViewById(R.id.txtHelloWorld);
txtAnotherText= findViewById(R.id.txtAnotherText);

3) Now what you want to achieve is that when the first text appears, the second text disappears, using a checkbox as a trigger.
You already have the function, so just add the case you need.
  1. private void updateTextVisibility(boolean isChecked) // When checking the trigger (checkbox)
  2. {
  3. if (isChecked)
  4. {
  5. txtHelloWorld.setVisibility(View.VISIBLE); // The first is visibile
  6. txtAnotherText.setVisibility(View.INVISIBLE); // and the second is invisible
  7. }
  8. else
  9. {
  10. txtHelloWorld.setVisibility(View.INVISIBLE);
  11. txtAnotherText.setVisibility(View.VISIBLE);
  12. }
  13. }
I hope I was able to help you, bye
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones