Search code examples
androidonclicklistener

How do I properly implement View.OnClickListener and use it with a TextView?


I am intending to assign a click listener to a TextView. First I implemented View.OnClickListener in MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ...
    TextView title = findViewById(R.id.title);
    title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ...
        }
    });
}

Then I set android:clickable="true" on the TextView.

However, despite overriding the onClick mehtod, an error pops up saying:

Class 'MainActivity' must either be declared abstract or implement abstract method 'onClick(View)' in 'OnClickListener'

What can I do to dodge this error?


Solution

  • The root of the issue is with your activity declaration and there are two ways to deal with it.

    • Let your activity implement the View.onClickListener and you pass the activity to the textview's setOnClickListener
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
        ...
        TextView title = findViewById(R.id.title);
        title.setOnClickListener(this);
    
        TextView title2 = findViewById(R.id.textview2);
        title2.setOnClickListener(this);
    
    
       // implement the onClick method in your MainActivity class
            @Override
            public void onClick(View view) {
                switch(view.getId()){
                   case R.id.TextView1 : //logic for textview1
                       break;
    
                   case R.id.TextView2: // logic for textview2
                       break;
                }
            }
    }
    
    • Modify your Activity function declaration and create a a new instance of View.OnClickListener in setOnClickListener method.
    public class MainActivity extends AppCompatActivity {
        ...
        TextView title = findViewById(R.id.title);
        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ...
            }
        });
    }