我有一个片段内的列表视图。我想填充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;
}
}
的'onActivityCreated()'方法完美地工作,谢谢。我认为它不会在正常的“片段”内工作 - 但它确实!干杯! –