mbwasi
mbwasi

Reputation: 4227

get first item only in a Android ListView?

How do you get the first list item in a listView? I want to get at a TextView in the first list item. I am currently doing this:

View listItem=(View)myList.getChildAt(0);
TextView txtDep=(TextView)listItem.findViewById(R.id.txtDepart);
txtDep.setText("Hello!");

But this is not only changing the text in the first item but in every 8th, 16th and so on items. I would like to change the text in the first(top) item only. Thank you.

Upvotes: 2

Views: 7769

Answers (5)

Even Cheng
Even Cheng

Reputation: 1996

Same symptom but different cause for me. I changed my fragment layout to a controlled height instead of match_parent and that solves my issue.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

to

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal" >

Upvotes: 0

Muhammad Aamir Ali
Muhammad Aamir Ali

Reputation: 21087

If you want to get the specific item in the list and want to change its color you can get this through getView method in your Adapter class.

@Override public View getView(int position, View convertView, ViewGroup parent) {

if(convertView == null)
{
    LayoutInflater inflater = (LayoutInflater)context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.crewlist_row, null);
}

TextView firstname = (TextView)convertView.findViewById(R.id.firstname);
firstname.setText(userArray.get(position).getFirstName());

return convertView;
}

Upvotes: 1

mikerowehl
mikerowehl

Reputation: 2238

What you want to do is change the data in the ListAdapter and then call the notifyDataSetChanged() method to get the list to re-render. See the discussion here, includes some sample code:

ListView adapter data change without ListView being notified

Upvotes: 0

Robby Pond
Robby Pond

Reputation: 73484

Views are recycled so your TextView will be used for many different items in the list. If you want to change what a specific item displays then you need to change the data that is behind your ListItem and is being served up by the ListAdapter (in the getView() method). So whenever the ListView shows the item in the list, the adapter will show the correct data in the TextView.

And when you change data in your list or whatever, you will need to call notifyDataSetChanged() on your adapter.

Upvotes: 5

Nanne
Nanne

Reputation: 64399

Shouldn't you use getItem(0) ?

http://developer.android.com/reference/android/widget/Adapter.html#getItem%28int%29

Upvotes: 0

Related Questions