如何在我的应用程序中添加两个listfragment

时间:2013-08-26 07:29:49

标签: android

我有一个应用程序,使用下面的代码显示第一个列表。如何点击下面代码中的任何列表项,在更多列表上显示。请帮我一个示例代码。

public class MyListFragment1 extends ListFragment {

    String[] VideoSetup ={
            "Properties", 
            "Color Control", 
            "Tint", 
            "3D Depth",
            "3D Format", 
            "Dynamic Backlight", 
            "Mode", 
            "Cache ID",

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListAdapter myListAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                VideoSetup);
        setListAdapter(myListAdapter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.listfragment1, container, false);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        Toast.makeText(
                getActivity(), 
                getListView().getItemAtPosition(position).toString(), 
                Toast.LENGTH_LONG).show();
        Fragment2 frag = (Fragment2) getFragmentManager().findFragmentById(R.id.fragment2);
    }




}

我不确定这样做。我对android很新。

1 个答案:

答案 0 :(得分:0)

首先,您必须编写第二个ListFragment。同样。

然后,在第一个Fragment的onListItemClick()方法中,您可以编写如下内容:

Fragment2 frag = (Fragment2) getFragmentManager().findFragmentById(R.id.fragment2);

activity.getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, frag)
                    .addToBackStack(null)
                    .commit();

这是你的片段容器 - /res/layout/activity_main.xml。它是空的。通过setContentView(R.layout.activity_main)将它与MainActivity.class绑定:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity"
                android:background="#000000"
                android:id="@+id/fragment_container">
</RelativeLayout>

之后,您必须在片段容器上添加新的第一个片段,如上所述。

然后,在第一个片段的onListItemClick(...)方法中,您必须创建新的第二个片段并首先替换。