sark9012
sark9012

Reputation: 5747

Need to target listview position on click android

I have a situation where I am trying to change the text within a TextView on a certain row being clicked in a ListView.

The following code shows how I try and do this:

    answerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

           TextView selection = (TextView)view.findViewById(R.id.selection);
           selection.setText("Selection");

       }
   });

Currently, when selecting any row from within the list view, the first row sets the text as desired.

How do I incorporate position in this to ensure that the correct row is displaying the text I require?

Thanks!

Upvotes: 0

Views: 171

Answers (5)

Sarthak Mittal
Sarthak Mittal

Reputation: 6104

I don't think that it's the most authentic way to do it, but i do it like this:

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    if (convertView == null)
    {
        convertView = inflater.inflate(R.layout.my_layout);     
        holder = new StoreHolder();         
        holder.tvData = (TextView) convertView.findViewById(R.id.my_data);
        convertView.setTag(holder);         
    }
    else
    {
        holder = (StoreHolder) convertView.getTag();
    }

    holder.tvData.setText("hello");     

    holder.tvData.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            //Do stuff specific to TextView of particular list row
        }
    });

    return convertView;
}

class StoreHolder
{
    TextView tvData;        
}

Just create a clickListener in the getview method for the textView and it will work perfectly!

Upvotes: 0

andrei
andrei

Reputation: 2940

If I understood correctly what you need, then you should just iterate over your list of objects inside onItemClick, change the property which is used to set the text view to an empty string for every element EXCEPT the i element, and call notifyDataSetChanged()

Upvotes: 0

Ravi Teja
Ravi Teja

Reputation: 54

You can do this with an AdapterView.OnItemClickListener. Implement the onItemClick(AdapterView parent, View view, int position, long id) method. The view you get passed here, is the TextView of the clicked item, so it should be enough to do

((TextView)view).setText("Hey, I've just been tapped on!");

Upvotes: 0

Ravi Teja
Ravi Teja

Reputation: 54

There you are getting integer value from onItemClick method write switch with i as parameter

Upvotes: 0

Rajat Mehra
Rajat Mehra

Reputation: 1482

in method :

public void onItemClick(AdapterView adapterView, View view, int i, long l)

int i gives the position, you can use this.

Upvotes: 2

Related Questions