gpt4 book ai didi

java - 如何使用FragmentTransaction的add()方法在RelativeLayout中设置Fragment

转载 作者:行者123 更新时间:2023-12-01 09:14:35 26 4
gpt4 key购买 nike

我正在使用从右向左滑动的抽屉布局,为了完成此任务,我创建了下面的方法:

XML 代码:

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<!-- Framelayout to display Fragments -->

<RelativeLayout
android:id="@+id/mainView"
android:layout_width="match_parent"
android:layout_height="match_parent" >


</RelativeLayout>

<!-- Listview to display slider menu -->

<RelativeLayout
android:id="@+id/drawerView"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_gravity="start" >

<ListView
android:id="@+id/list_slidermenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/list_background"
android:divider="@color/list_divider"
android:dividerHeight="1dp" />
</RelativeLayout>

Java 代码:

public class ProfileActivity extends ActionBarActivity {
....
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;

RelativeLayout drawerView;
RelativeLayout mainView;
....

@Override
protected void onCreate(Bundle savedInstanceState) {


............. //
.............//
drawerView = (RelativeLayout) findViewById(R.id.drawerView);
mainView = (RelativeLayout) findViewById(R.id.mainView);

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
supportInvalidateOptionsMenu();
}

public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu();
}

@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
mainView.setTranslationX(slideOffset * drawerView.getWidth());
mDrawerLayout.bringChildToFront(drawerView);
mDrawerLayout.requestLayout();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);

}
}

所以我想通过代码在RelativeLayout中添加Fragment。

有什么想法吗?

最佳答案

    FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
View containerView = findViewById(R.id.mainView);
ft.add(R.id.mainView, fragment);
ft.commit();
fm.executePendingTransactions();

您可以在 onCreate() 中调用此代码。

关于java - 如何使用FragmentTransaction的add()方法在RelativeLayout中设置Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40659477/

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