如何获得listView中的第一个列表项?我想在第一个列表项中找到TextView。 我目前正在这样做:
View listItem=(View)myList.getChildAt(0);
TextView txtDep=(TextView)listItem.findViewById(R.id.txtDepart);
txtDep.setText("Hello!");
但这不仅改变了第一个项目中的文本,而且改变了每个第8个,第16个等项目。我想仅更改第一个(顶部)项目中的文本。 谢谢。
答案 0 :(得分:5)
视图被回收,因此您的TextView将用于列表中的许多不同项目。如果要更改特定项目显示的内容,则需要更改ListItem后面的数据,并由ListAdapter(在getView()方法中)提供。因此,只要ListView显示列表中的项目,适配器就会在TextView中显示正确的数据。
当您更改列表中的数据或其他内容时,您需要在适配器上调用notifyDataSetChanged()。
答案 1 :(得分:1)
如果您想获取列表中的特定项目并想要更改其颜色,可以通过Adapter类中的getView方法获取此颜色。
@覆盖 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;
}
答案 2 :(得分:0)
你不应该使用getItem(0)
吗?
http://developer.android.com/reference/android/widget/Adapter.html#getItem%28int%29
答案 3 :(得分:0)
您要做的是更改ListAdapter中的数据,然后调用notifyDataSetChanged()
方法以获取要重新呈现的列表。请参阅此处的讨论,包括一些示例代码:
ListView adapter data change without ListView being notified
答案 4 :(得分:0)
症状相同但对我不同。我将片段布局更改为受控高度而不是match_parent,这解决了我的问题。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
到
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal" >