简体   繁体   中英

Android … Can I have 2 fragments on 1 tab, without them overlapping?

I'm using actionbarsherlock to create an app that has tabs, with a list of each tab. I'd like for there to be an admob ad at the bottom of the list on all tabs. I've gotten it close to working, but the fragments are overlapping instead of having the list above the ad. Here's the code:

public void onTabSelected(Tab tab, FragmentTransaction ft) {

    ListFragment = new FragmentTab1();
    ft.add(android.R.id.content, ListFragment);
    ft.attach(mFragment);

    Fragment adfragment = new AdFragment();
    ft.add(android.R.id.content, adfragment);
    ft.attach(adfragment);
}

It's almost like I want to concat the 2 fragments before adding them to the transaction, but I can't figure that out.

You need to create a custom layout with two FrameLayout like this . So the Ads will be at the bottom with a fixed height and ListView Fragment will use the remaining height.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/list_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/Red"
    android:layout_weight="1"/>

<FrameLayout
    android:id="@+id/ads_container"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@color/Yellow"/>
</LinearLayout>

And add the Fragments to each FrameLayout like this

ListFragment = new FragmentTab1();
ft.add(R.id.list_container, ListFragment);
ft.attach(mFragment);

Fragment adfragment = new AdFragment();
ft.add(R.id.ads_container, adfragment);
ft.attach(adfragment);

Try to use ViewPager.

Below is one of the link for ViewPager example

http://www.edumobile.org/android/android-beginner-tutorials/view-pager-example-in-android-development/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM