So I have this simple main layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="@layout/top_bar" />
<android.support.v4.view.ViewPager
android:id="@+id/VpPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Then I use a FragmentPagerAdapter to fill the ViewPager with different fragments, which works as expected, except for one thing.
Let's say one of the fragments has this layout, where window is an XML-file containing a simple shape with rounded corners:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical"
android:background="@drawable/window">
...
</LinearLayout>
Then, for some reason, the margin of 16dp is completely ignored. But if I set the layout to:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical"
android:background="@drawable/window">
...
</LinearLayout>
</FrameLayout>
Then it works. I really don't want to nest the whole layout in another just to make the margin work. Plus, because of the background, I can't use padding instead. Any idea what the problem is with the first version? Any alternatives where I don't have to put the layout in another?
yes...you can use View instead of Fragment in viewpager. Here you can Find Whole example that will help you to achieve Viewpager without Fragment. Go through this documentation. Save this answer.
To use ViewPager and tabs, you need to add a dependency on ViewPager and on Material Components to your project. To insert child views that represent each page, you need to hook this layout to a PagerAdapter .
Steps for implementing viewpager: Adding the ViewPager widget to the XML layout (usually the main_layout). Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class.
The reason for this is that margins are not supported by the ViewPager.LayoutParams, as you can see from the documentation.
However, FrameLayout.LayoutParams does support ViewGroup.MarginLayoutParams, which is why wrapping your LinearLayout inside a FrameLayout actually does provide the results you're seeking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With