我在应用程序主活动布局中使用以下代码
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.keyhan_soft.gps.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email"/>
</android.support.design.widget.CoordinatorLayout>
如您所见,我在
<include layout="@layout/content_main"/>
行中包含了片段布局,但这是静态方式,我如何用动态FrameLayout
解决方案替换这种静态方式?我想以编程方式添加片段
最佳答案
您可以尝试以下方法来执行FragmentTransaction
来替换Fragment
布局中的content_main
。以下方法用于FragmentTransaction
。
方法:
public void pushFragments(Fragment fragment, boolean shouldAdd, String tag) {
FragmentManager manager = getSupportFragmentManager();//Use this line for FragmentManager , if you are in Activity
//FragmentManager manager = getActivity().getSupportFragmentManager();//Use this line for FragmentManager , if you are in Fragment
FragmentTransaction ft = manager.beginTransaction();
//manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//Uncomment this line if you don't want to maintain Fragment Backsack
ft.replace(R.id.content_main, fragment, tag);
if (shouldAdd) {
ft.addToBackStack(tag); //add fragment in backstack
}
ft.commit();
}
我给出了如何做
FragmentTransaction
的例子。YourFragment.java
public class YourFragment extends BaseFragment {
private View rootView;
public YourFragment() {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.layout_your_fragment, container, false);
return rootView;
}
}
例:
pushFragments(new YourFragment(),
true, // true --> add Fragment in backstack else false
"YourFragment"); // Fragment tag which help to find your fragment
希望对您有所帮助。
关于android - Android实现CoordinatorLayout和Framelayout,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34356425/