1. Are you ready for the Galaxy S20? Here is everything we know so far!

Checkbox to show/hide textview

Discussion in 'Android Development' started by little_star, Jul 17, 2021.

  1. little_star

    little_star Lurker
    Thread Starter

    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 (Text):
    1. Import ...
    2. public class MainActivity extends AppCompatActivity {
    3.  
    4.     private TextView txtHelloWorld;
    5.  
    6.    @Override
    7.     protected void onCreate(Bundle savedInstanceState) {
    8.        super.onCreate(savedInstanceState);
    9.        setContentView(R.layout.activity_main);
    10.        CheckBox checkBoxVisibility = findViewById(R.id.checkBox_visibility);
    11.        txtHelloWorld = findViewById(R.id.txtHelloWorld);
    12.        boolean isChecked = checkBoxVisibility.isChecked();
    13.        updateTextVisibility(isChecked);
    14.        checkBoxVisibility.setOnClickListener(v -> {
    15.  
    16.            boolean isChecked1 = ((CheckBox)v).isChecked();
    17.            updateTextVisibility(isChecked1);
    18.        });
    19.    }
    20.     private void updateTextVisibility(boolean isChecked) {
    21.         if (isChecked) {
    22.             txtHelloWorld.setVisibility(View.VISIBLE);
    23.         } else {
    24.             txtHelloWorld.setVisibility(View.INVISIBLE);
    25.         }
    26.     }
    27. }
     



    1. Download the Forums for Android™ app!


      Download

       
  2. Askautmir

    Askautmir Lurker

    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
     
Loading...

Share This Page

Loading...