2012-02-19 40 views
1

我有一個ListFragment,其中包含一個列表,但onListItemClick永遠不會被調用。我沒有使用我懷疑是問題的getListView()。我從XML拉着我的列表視圖,例如:onListItemClick不在ListFragment中調用

list = (ListView) getActivity().findViewById(android.R.id.list); 

,然後設置適配器這樣的:

list.setAdapter(new CustomAdapter(getActivity(), R.layout.title, mCursor, new String[]{"title"}, new int[]{R.id.my_title})); 

因爲我需要設置適配器就行了,我不使用setListAdapter ()。是不可能從XML中拉出列表並使用onListItemClick?我想保留我的列表視圖在XML中,所以我不必以編程方式設置所有的屬性。

如果這不可行,我該如何選擇列表中的項目?

謝謝

+1

我不清楚爲什麼你不使用標準模式。在ListFragment上調用setListAdapter,將它傳遞給你的Customadapter。你可以做到這一點,並仍然通過在newView中擴展它來在佈局中定義列表。您可能通過不調用setListAdapter來繞過某些代碼。 – 2012-02-19 05:24:27

回答

0

好的。試試這個答案。保持您的佈局文件原樣。覆蓋下面的方法在您的FragmentList類:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) 
{ 
    return inflater.inflate(R.layout.your_fragment_layout, container, false); 
} 

請確保您的佈局定義與正確的ID一個ListView,如下:

<ListView android:id="@id/android:list" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:drawSelectorOnTop="false"/> 

然後,只需調用FragmentList :: setListAdapter:

setListAdapter(new CustomAdapter(getActivity(), R.layout.title, mCursor, new String[]{"title"}, new int[]{R.id.my_title})); 

應該工作,ticky-boo。

+1

它看起來不像我可以重寫ListFragment內的newView。我可以從我的CustomAdapter中擴展SimpleCursorAdapter,但是,我不認爲這是它的適當位置。 – Nick 2012-02-19 05:50:35

+0

我已經更新了答案。我從錯誤的地方抓起了代碼。該方法是相同的,但覆蓋onCreateView。 – 2012-02-19 06:39:09

+0

謝謝。沒有onCreateView是什麼導致xml列表不被顯示。 – Nick 2012-02-21 17:23:06