i have the following layout
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
Everyting is workinf fine but i want to replace the ViewPager with a Fragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.view_pager, new CustomFragment())
.commit();
this is not repacing the ViewPager what shall i do???
You could create a Fragment that contains the ViewPager, and then replace that Fragment.
public class ViewPagerContainerFragment extends Fragment {
private ViewPager mViewPager;
public ViewPagerContainerFragment() { }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.view_pager_container_fragment, container, false);
// Set up the ViewPager, attaching the adapter and ...
mViewPager = (ViewPager) root.findViewById(R.id.viewPager);
// do other stuff...
return root;
}
}
view_pager_container_fragment.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/rlMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
Your Activitys .xml file:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
And then replace Fragments like this:
Adding the ViewPagerContainerFragment to the Activitys layout:
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, new ViewPagerContainerFragment())
.commit();
And somewhere later in code: (if you want to - replace the ViewPagerFragment with another Fragment)
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, new CustomFragment())
.commit();
Please make sure that you do not create any memory leaks and set up your Adapter properly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.