Search code examples
androidonclicklistener

Android - setOnClickListener for TextView


It should be straightforward, but I am not sure where something is wrong. I try to catch the click on the TextView with:

public void runNextTask(){
    final View addView = getLayoutInflater().inflate(R.layout.addnewtracker, null);
    final TrackerInfo newInfo = new TrackerInfo();
    //set up for model selection
    TextView modelTextview = (TextView)addView.findViewById(R.id.modelEdit)

    modelTextview.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
}

Thee XML for the TextView is:

<TextView
    android:id="@+id/model"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Tracker_model" 
    android:clickable="true"
    android:onClick="onClick"/>

But when I click on the TextView, it does not go into the onClick() method. What am I missing?

Thanks


Solution

  • You can remove this:

    android:onClick="onClick"
    

    Or, remove this:

    modelTextview.setOnClickListener(new OnClickListener() {
        @Override
         public void onClick(View v) {
    
         }
    });
    

    and have this:

    public void onClick(View v)
    {
        // do something
    }  
    

    android:onClick="onClick"/> // It would be better to rename the method to avoid confusion

    Also, you have this:

    <TextView
         android:id="@+id/model" // id is model
    

    so initialize your TextView as below:

    TextView modelTextview = (TextView)addView.findViewById(R.id.model);