Search code examples
javaandroidonclicklistener

Android studio how to know which textview was clicked?


I'm basically building a small quiz app and for every question, there are 4 answers in 4 different textviews. What I want to know is which textview has been clicked by the user.


Solution

  • You can easily do this by applying onClickListeners to the textViews, Following code may help :

    TextView mTvAnswer1, mTvAnswer2, mTvAnswer3, mTvAnswer4;
    mTvAnswer1 = findViewById(R.id.text_1);
    // similarly find other textviews
    
    mTvAnswer1.setOnClickListener(this);
    mTvAnswer2.setOnClickListener(this);
    mTvAnswer3.setOnClickListener(this);
    mTvAnswer4.setOnClickListener(this);
    

    And after this in you can override onClick() as follows:

    @Override
    public void onClick(View v){
    switch (v.getId()){
         case R.id.text1:
             // First option clicked
             break;
         case R.id.text2:
            // Second option clicked
            break;
         case R.id.text3:
             // Third option clicked
             break;
         case R.id.text4:
             // Fourth option clicked
             break;
    

    } }