Skip to content
Advertisement

How to Visible/Invisible using OnClickListener?

I am working on FAQ page I don’t want to use Expandable list view and stuff. So I set 2 TextViews(1 for Question and 1 for Answer) and made one clickable.

working onclick

The above image shows when the first textview mfaq is clicked it sets second one mAns to visible.

The below code works well to Set the mAns textview visible:

public class faq extends AppCompatActivity {
TextView mfaq,mAns;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_faq);

    mfaq=findViewById(R.id.faq);
    mAns=findViewById(R.id.ans);

    mfaq.setOnClickListener(new View.OnClickListener() {
        int counter=0; //setting counter to count onclick
        @Override
        public void onClick(View view) {
            ++counter; //incrementing counter first click
            if(counter==1){
                mAns.setVisibility(View.VISIBLE);
            }
            //this sets mAns visible , but when i click on it again i want it to hide the text view
            counter=0; //resetting the counter
        }
    });
}
}

So I want to set the visibilty to gone when the textview is clicked again(Should function like Click-visible,ClickAgain-Invisible,Repeat). Note-I am a beginner please try to explain me what the code is doing so I learn more 🙂 Thanks.

Advertisement

Answer

If I understand well you wanna hide/show your textview each time you click on the other text?

            mfaq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mAns.getVisibility() == View.VISIBLE){
                    mAns.setVisibility(View.GONE);
                }
                else
                    mAns.setVisibility(View.VISIBLE);
             }
        });
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement