OnListItemClick打开一个新的片段

时间:2014-01-03 01:46:46

标签: java android android-fragments

我正在使用“Action bar Sherlock”和“SlidingMenu”库。 我有一个包含5个项目的列表,我想在单击列表中的项目时更改片段。 这是我的代码到目前为止,我正在尝试使用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**
    }
}

1 个答案:

答案 0 :(得分:3)

如果你的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);
}