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 开发者_Python百科on items. I would like to change the text in the first(top) item only. Thank you.
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.
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;
}
Shouldn't you use getItem(0)
?
http://developer.android.com/reference/android/widget/Adapter.html#getItem%28int%29
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
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" >
精彩评论