Библиотека поддержки дизайна Android TabLayout с использованием настраиваемого макета вкладок, но макет, обертывающий вкладки

В пользовательском макете вкладки я установил для его родительского элемента значение match_parent и установил цвет фона. Когда я запускаю его, на вкладках отображается пользовательский макет, обертывающий элементы изображения и текста. Я хочу, чтобы этот пользовательский макет заполнил вкладку без пробелов между вкладками. Проверьте вывод здесь: Скриншот вкладок

private void setupTabLayout(ViewPager viewPager, ViewPagerAdapter viewPagerAdapter) {
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.setupWithViewPager(viewPager);

    int length = tabLayout.getTabCount();
    for (int i = 0; i < length; i++) {
        tabLayout.getTabAt(i).setCustomView(viewPagerAdapter.getTabView(i));
    }
}

tab_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout"
    android:background="@color/grey_accent">

    <ImageView
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/icon"
        android:src="@drawable/ic_action_home"
        android:layout_marginBottom="19dp"
        android:layout_above="@+id/title"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home"
        android:id="@+id/title"
        android:layout_marginBottom="259dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Вьюпагерадаптер:

public View getTabView(int position) {
    View view = LayoutInflater.from(this.context).inflate(R.layout.tab_layout, null);
    TextView title = (TextView) view.findViewById(R.id.title);
    ImageView icon = (ImageView) view.findViewById(R.id.icon);
    ViewGroup layout = (ViewGroup) view.findViewById(R.id.layout);

    layout.setBackgroundResource(this.mColorList.get(position));
    icon.setImageResource(this.mIconList.get(position));
    title.setText(this.getPageTitle(position));

    return view;
}



Ответы (5)


Попробуй это

<android.support.design.widget.TabLayout
    app:tabPaddingStart="-1dp"
    app:tabPaddingEnd="-1dp"/>

Я нашел его здесь

person Mark    schedule 20.08.2015
comment
app:tabPaddingStart="0dp" app:tabPaddingEnd="0dp" работает на меня. - person offset; 18.10.2015
comment
Это вообще не работает для Scrollable Tablayout - person Colateral; 13.03.2016

Вы можете использовать вкладку Material Design, а затем настроить пользовательский вид для всех вкладок. Для полной справки посетите: Пример пользовательского табло

Пользовательский вид для всех вкладок может быть примерно таким:

<?xml version="1.0" encoding="utf-8"?>

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/ll"
        android:orientation="horizontal"
        android:layout_weight="1"
        android:gravity="center">

        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@mipmap/ic_launcher"/>
        <TextView
            android:id="@+id/tvtab1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ONE"
            android:textColor="@color/colorAccent"
            android:textSize="14sp"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/ll2"
        android:orientation="vertical"
        android:gravity="center">
        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@mipmap/ic_launcher"/>

        <TextView
            android:id="@+id/tvtab2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TWO"
            android:textColor="#26e9dc"
            android:textSize="14sp"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/ll3"
        android:orientation="vertical"
        android:gravity="center">

        <TextView
            android:id="@+id/tvtab3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="THREE"
            android:textColor="#d8ea2b"
            android:textSize="14sp"
            android:textStyle="bold" />
        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@mipmap/ic_launcher"/>
    </LinearLayout>
</LinearLayout>

код для XML-файла активности (activity_main.xml)

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="#fff"
            app:tabSelectedTextColor="#000"
            app:tabGravity="fill"
            app:tabMode="fixed" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

Наконец, код для MainActivity.java

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    public ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        View headerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.custom_tab, null, false);

        LinearLayout linearLayoutOne = (LinearLayout) headerView.findViewById(R.id.ll);
        LinearLayout linearLayout2 = (LinearLayout) headerView.findViewById(R.id.ll2);
        LinearLayout linearLayout3 = (LinearLayout) headerView.findViewById(R.id.ll3);

        tabLayout.getTabAt(0).setCustomView(linearLayoutOne);
        tabLayout.getTabAt(1).setCustomView(linearLayout2);
        tabLayout.getTabAt(2).setCustomView(linearLayout3);

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "ONE");
        adapter.addFragment(new TwoFragment(), "TWO");
        adapter.addFragment(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}
person user6435056    schedule 02.06.2017

Добавление нескольких вкладок

Шаг 1. Добавьте код макета xml для пользовательских вкладок.

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true">
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        android:background="@color/white"
        app:tabGravity="center" />

</android.support.design.widget.AppBarLayout>


<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_marginBottom="50dp"/>

Шаг 2: Java-код для активности вкладок

public class BookingsTabs extends AppCompatActivity {
    String url, smobile, snames, semail, sid, stoken, responseServer;
    String id, token, did, stsid, processresponse, type, cancelresponse;
    TextView tv1;
    Button cretedeal;
    ViewbookingsAdapter adapter;
    ViewbookingsAdapter2 adapter2;
    LinearLayout order;
    private Tracker mTracker;
    ProgressDialog pDialog;
    ListView listview;
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    AnalyticsApplication application1;
    SessionManagement session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_bookings);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            ActionBar actionBar = getSupportActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(true);
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setDisplayUseLogoEnabled(false);
            actionBar.setHomeButtonEnabled(true);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
        }
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        int defaultValue = 0;
        int page = getIntent().getIntExtra("TAB", defaultValue);
        viewPager.setCurrentItem(page);
        application1 = (AnalyticsApplication) getApplication();
        mTracker = application1.getDefaultTracker();
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.accentColor));
        tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.aquablue));

        tabLayout.getTabAt(0).setCustomView(R.layout.aquablue);
        tabLayout.getTabAt(1).setCustomView(R.layout.orangeprocess);
        tabLayout.getTabAt(2).setCustomView(R.layout.shipping);
        tabLayout.getTabAt(3).setCustomView(R.layout.deliver);
        tabLayout.getTabAt(4).setCustomView(R.layout.completedtxt);
        tabLayout.getTabAt(5).setCustomView(R.layout.cancelled);

        callAsynchronousTask();
        viewPager.setCurrentItem(0);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OrderplacedFragment(), "Order Placed");
        adapter.addFrag(new ProcessingFragment(), "Processing");
        adapter.addFrag(new ShippingFragment(), "Shipping");
        adapter.addFrag(new DeliveredFragment(), "Delivered");
        adapter.addFrag(new CompletedFragment(), "Completed");
        adapter.addFrag(new CancelledFragment(), "Cancelled");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {

            }
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

Шаг 3: я добавил фрагмент кода вкладки ниже для одной вкладки, такой же, как и для других вкладок.

Возьмите xml-код любого списка или некоторых данных

public class OrderplacedFragment extends Fragment {
    View mMainView;
    String url, smobile, snames, semail, sid, stoken, responseServer;
    Context context;
    ViewbookingsAdapter adapter;
    ViewbookingsAdapter2 adapter2;
    ListView listview;
    LinearLayout tv1;
    TextView create;
    ArrayList<HashMap<String, String>> processlist, hatfilterslist;
    SessionManagement session;
    private SwipeRefreshLayout mSwipeRefreshLayout = null;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mMainView = inflater.inflate(R.layout.listview_orderbookings, container, false);

        listview = (ListView) mMainView.findViewById(R.id.listview);

        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...");
        pDialog.setMax(5);
        Intent j = getActivity().getIntent();
        coupon_code = j.getStringExtra("code");
        create = (TextView) mMainView.findViewById(R.id.dealslist);
        tv1 = (LinearLayout) mMainView.findViewById(R.id.no_deals_linear);
        create = (TextView) mMainView.findViewById(R.id.dealslist);
        create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(getActivity(), MyDealsActivity.class);
                startActivity(i);

            }
        });
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(getActivity(), MyDealsActivity.class);
                startActivity(i);
            }
        });

        return mMainView;
    }
}

В этих вкладках мы также можем добавить счетчики. Если у вас есть какие-либо вопросы по этому поводу, спросите меня

person Venkatesh    schedule 03.01.2017

Когда вы используете inflate(R.layout.tab_layout, null), вы говорите, что родителя View вообще нет. Это приведет к тому, что все атрибуты layout_ будут отброшены в соответствии с этим советом.

Вместо этого вы должны передать TabLayout и false (т. е. не присоединять автоматически View): это гарантирует, что атрибуты не будут проигнорированы.

public View getTabView(TabLayout tabLayout, int position) {
    View view = LayoutInflater.from(this.context)
        .inflate(R.layout.tab_layout, tabLayout, false);
    TextView title = (TextView) view.findViewById(R.id.title);
    ImageView icon = (ImageView) view.findViewById(R.id.icon);
    ViewGroup layout = (ViewGroup) view.findViewById(R.id.layout);

    layout.setBackgroundResource(this.mColorList.get(position));
    icon.setImageResource(this.mIconList.get(position));
    title.setText(this.getPageTitle(position));

    return view;
}
person ianhanniballake    schedule 08.08.2015
comment
Я пробовал, как вы сказали, но это не работает, я получаю тот же результат. - person ; 08.08.2015

используйте приложение: tabMaxWidth="44dp" приложение:tabMinWidth="44dp"

person Andrey Uglev    schedule 09.11.2016