2011-02-09 151 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" > 
相關問題