0

我们如何以编程方式转换以下 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>

4

2 回答 2

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();
于 2013-11-14T06:21:05.353 回答
1

this may help you...

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;
}
于 2013-11-14T06:46:32.423 回答