Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 252
batuman Avatar asked Jul 13 '13 13:07

batuman


People also ask

What does setOnClickListener do in Android?

setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface.

Does Android have OnClickListener?

In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.

How will you add a click to a TextView and how is the route of the click set?

We will use this TextView to set on-click listener. Get reference to the the TextView in layout file using id, and then call setOnClickListener {} on this TextView. When user clicks on this TextView, the code inside setOnClickListener {} will be executed.

Is onClick deprecated in Android?

onClick is prompted deprecated.


1 Answers

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);
like image 182
Raghunandan Avatar answered Sep 17 '22 18:09

Raghunandan