gpt4 book ai didi

java - OnListItem点击打开一个新的Fragment

转载 作者:行者123 更新时间:2023-12-01 23:18:16 24 4
gpt4 key购买 nike

我正在使用“Action bar Sherlock”和“SlidingMenu”库。我有一个包含 5 个项目的列表,我想在单击列表中的项目时更改 fragment 。到目前为止,这是我的代码,我正在尝试使用 OnListItemClick 但我真的不知道如何使用它。

public class RandomList extends SherlockListFragment {

String[] list_contents = {"Page 1", "Page 2", "Page 3", "Page 4", "Page 5" };

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
// return super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.list, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list_contents));
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);

// **Open different fragment after click**
}
}

最佳答案

如果您的 fragments 之一(我们称之为 MyFragment)与 SlidingMenu 中的第一项相关:

public class MyFragment extends Fragment {

public static Fragment newInstance(...) {
MyFragment f = new MyFragment();
// Since fragments require that you have a
// public constructor with zero arguments, then
// we use this pattern to initialize the fragment.
...
return f;
}
...
}

您可以使用 switch 语句:

void callFragmentFromDrawer(int position) {
Fragment f = null;
switch (position) {
case 0:
f = MyFragment.newInstance();
break;
case 1:
...
}

if (f != null) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, f)
.addToBackStack(list_contents[position])
.commit();
}
}

那么,

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
callFragmentFromDrawer(position);
}

关于java - OnListItem点击打开一个新的Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20895164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com