2014-01-12 92 views
0

我有一個片段內的列表視圖。我想填充listview一旦它被充氣和引用。使用視圖內的片段創建

我的第一次嘗試是引用片段的onCreate方法中的列表視圖,但它還沒有被onCreateView方法膨脹,因此不能進行引用,並且列表保留爲空。

然後我嘗試引用onCreateView方法中的列表,如某些人所建議的。然而這似乎被稱爲之後onCreate方法。因此,我不能在onCreate方法中進行任何初始化,並且onCreateView似乎是放置我的初始化代碼(例如設置列表適配器)的不好的地方。什麼是膨脹和引用片段內的列表視圖的正確方法,然後立即開始在代碼中使用列表視圖?

public class FragmentList extends Fragment { 

    ListView list; 
    List<Item> itemList; 
    ListAdapter adapter;   
    Context context; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    {   
      itemList = getItemList(); 
      context = getCtxt(); 

     adapter = new ListAdapter(itemList, context); 
     if (list != null && adapter != null) 
      list.setAdapter(adapter); // never reached, as list is always null here 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) {   
     // Inflate the layout for this fragment 

     View v = inflater.inflate(R.layout.fragment_list, container, false); 

     list = (ListView) v.findViewById(R.id.list); 

     return v; 
    } 
} 

回答

1

如果你的片段只包含一個ListView您應該擴展ListFragment和onActivityCreated填充它()。

+0

的'onActivityCreated()'方法完美地工作,謝謝。我認爲它不會在正常的「片段」內工作 - 但它確實!乾杯! –

1

你誤會了lifecycle of Fragment。 我建議你看看文檔。

要知道,你的onCreate比onCreateView

之前調用

不要保留上下文參考因爲片段可以分離和上下文並不總是有效的。

嘗試類似這樣的東西。

公共類FragmentList延伸片段{

ListView list; 
List<Item> itemList; 
ListAdapter adapter;   
Context context; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) {   
    // Inflate the layout for this fragment 
    View v = inflater.inflate(R.layout.fragment_list, container, false); 
    list = (ListView) v.findViewById(R.id.list); 
    return v; 
} 

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState);  
    itemList = getItemList(); 
    adapter = new ListAdapter(itemList, getActivity()); 
    list.setAdapter(adapter); 
} 

}

+0

謝謝,這是非常有用的建議,我會看看。 –