2011-02-09 153 views
2

如何获得listView中的第一个列表项?我想在第一个列表项中查看TextView。 我目前这样做:仅在Android ListView中获取第一项?

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

但是,这不仅改变中的第一项,但在每一个第8,第16和等项目的文本。我想只改变第一个(顶部)项目中的文字。 谢谢。

+0

这是因为怎样的ListView作品可能。每次滚动时,列表顶部都有一个新项目,因此列表顶部的当前项目将为getChildAt(0);.您需要更改背景中的数据才能正确执行此操作。更改适配器的数据是更新列表视图的最佳方式,因为您经历了什么。 – ice911 2011-02-09 17:02:19

回答

5

查看被回收所以你的TextView将用于列表中的许多不同的项目。如果你想改变一个特定的项目显示,那么你需要改变ListItem后面的数据,并由ListAdapter(在getView()方法中)提供。所以无论何时ListView显示列表中的项目,适配器都将在TextView中显示正确的数据。

而当您更改列表中的数据或其他内容时,您需要在适配器上调用notifyDataSetChanged()。

+0

这是行之有效的。感谢名单 – mbwasi 2011-02-10 19:53:20

1

如果你想在列表中的特定项目,并希望改变其颜色,您可以通过getView方法在你的适配器类得到这个。

@覆盖 公共查看getView(INT位置,查看convertView,ViewGroup以及母公司){

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; 
} 
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" > 
相关问题