如何从ListFragment中的Activity添加项目?
public class LoadObjects extends ListFragment
{
String data[] = new String[] { "one", "two", "three", "four" };
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1,
data);
setListAdapter(adapter);
}
}
如何在此FragmentList中上传Activity的菜单项?请举例或链接。
答案 0 :(得分:0)
将适配器保存为实例变量,以便可以从任何位置引用它。然后,您可以从活动中为其添加项目。
public class LoadObjects extends ListFragment
{
String data[] = new String[] { "one", "two", "three", "four" };
public ArrayAdapter<String> mAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1,
data);
setListAdapter(mAdapter);
}
}
然后从您的活动更新ListFragment的ListView:
FragmentManager fManager = getFragmentManager();
LoadObjects frag = (LoadObjects) fManager.findFragmentByTag("listFragment");
if (frag != null) {
frag.mAdapter.addAll(youNewData);
}
当然请注意,在创建LoadObjects片段时,您需要为它设置一个标记:
LoadObjects frag = new LoadObjects();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, frag, "listFragment");
transaction.commit();