以编程方式创建列表片段和片段

时间:2013-11-14 05:49:49

标签: android android-fragments fragment android-listfragment

我们如何以编程方式转换下面的xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/list_fragment"
        android:name="com.aaa.bbb.activity.FragmentedListActivity$MyListFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#27577f" />

    <fragment
        android:id="@+id/detail_fragment"
        android:name="com.aaa.bbb.activity.FragmentedListActivity$MyDetailFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" />
</LinearLayout>

2 个答案:

答案 0 :(得分:1)

您可以将fragment代码更改为FrameLayout代码,删除每个代码中的属性名称,然后以编程方式添加代码:

MyListFragment fragment = new MyListFragment();
    MyDetailFragment fragment2 = new MyDetailFragment();
    fragmentTransaction.add(R.id.list_fragment, fragment);
    fragmentTransaction.add(R.id.detail_fragment, fragment2);
    fragmentTransaction.commit();

答案 1 :(得分:1)

这可能对你有帮助......

private static final int ID_MY_FRAGMENT = 0xDEAF1;
private static final int ID_MY_DETAIL_FRAGMENT = 0xDEAF2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View contentView = getView();
    setContentView(contentView);
    getSupportFragmentManager().beginTransaction()
            .replace(ID_MY_FRAGMENT, new MyListFragment())
            .replace(ID_MY_DETAIL_FRAGMENT, new MyDetailFragment()).commit();
}

private View getView() {
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.HORIZONTAL);

    FrameLayout frameLayout = new FrameLayout(this);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
    frameLayout.setLayoutParams(layoutParams);
    frameLayout.setId(ID_MY_FRAGMENT);
    layout.addView(frameLayout);

    View view = new View(this);
    layoutParams = new LinearLayout.LayoutParams((int) (1 * getResources()
            .getDisplayMetrics().density),
            LinearLayout.LayoutParams.MATCH_PARENT);
    view.setLayoutParams(layoutParams);
    view.setBackgroundColor(27555);
    layout.addView(view);

    frameLayout = new FrameLayout(this);
    layoutParams = new LinearLayout.LayoutParams(0,
            LinearLayout.LayoutParams.MATCH_PARENT, 2);
    frameLayout.setLayoutParams(layoutParams);
    frameLayout.setId(ID_MY_DETAIL_FRAGMENT);
    layout.addView(frameLayout);
    return layout;
}