Как установить разделитель между вкладками в TabLayout библиотеки поддержки дизайна?
Я использую новую библиотеку android.support.design.widget.TabLayout
библиотеки v7-appcompat
и обнаружил проблему, нет способа установить разделитель между вкладками, не знаю, есть ли.
Я успешно настроил адаптер пейджера, и вкладки выглядят хорошо, но не могут установить разделитель между вкладками.
Я хочу этот тип вкладок
Tab1 | Tab2 | Tab3
но в настоящее время отображается
Tab1 Tab2 Tab3
Мой 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" >
<include layout="@layout/toolbar" />
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_tabbar_background"
app:tabIndicatorColor="@android:color/white"
app:tabIndicatorHeight="4dp" />
</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>
Я добавляю вкладки этого
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(2);
adapter = new TabAdapterLoginActivity(getSupportFragmentManager(),
titles);
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
Ответы
Ответ 1
Существует способ добавить разделитель с помощью метода Tab
setCustomView:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
RelativeLayout relativeLayout = (RelativeLayout)
LayoutInflater.from(this).inflate(R.layout.tab_layout, tabLayout, false);
TextView tabTextView = (TextView) relativeLayout.findViewById(R.id.tab_title);
tabTextView.setText(tab.getText());
tab.setCustomView(relativeLayout);
tab.select();
}
Пользовательский макет вкладки с разделителем (tab_layout.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Tab title -->
<TextView
android:id="@+id/tab_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="@drawable/tab_item_selector"/>
<!-- Tab divider -->
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="@android:color/black" />
</RelativeLayout>
Установите вкладку TabLayout в горизонтальном отступе до 0dp
:
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_tabbar_background"
app:tabIndicatorColor="@android:color/white"
app:tabIndicatorHeight="4dp"
app:tabPaddingStart="0dp"
app:tabPaddingEnd="0dp" />
И селектор цвета текста заголовка вкладки при его выборе (tab_item_selector.xml):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="@color/abc_primary_text_material_dark" />
<item android:state_focused="true" android:color="@color/abc_primary_text_material_dark" />
<item android:state_pressed="true" android:color="@color/abc_primary_text_material_dark" />
<item android:color="@color/abc_secondary_text_material_dark" />
</selector>
Ответ 2
TabLayout
на самом деле HorizontalScrollView
, а первый ребенок - LinearLayout
.
Так просто используйте ниже код для добавления разделителей
View root = tabLayout.getChildAt(0);
if (root instanceof LinearLayout) {
((LinearLayout) root).setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
GradientDrawable drawable = new GradientDrawable();
drawable.setColor(getResources().getColor(R.color.separator));
drawable.setSize(2, 1);
((LinearLayout) root).setDividerPadding(10);
((LinearLayout) root).setDividerDrawable(drawable);
}
Ответ 3
Дизайн вкладки по умолчанию должен соответствовать спецификациям дизайна материалов. Если вам нужно добавить разделитель, рассмотрите возможность использования пользовательского представления для вкладки.
Проверяя эту ссылку вы можете управлять только ниже в свойствах стиля TabLayout без использования пользовательского представления
<style name="Base.Widget.Design.TabLayout" parent="android:Widget">
<item name="tabMaxWidth">@dimen/tab_max_width</item>
<item name="tabIndicatorColor">?attr/colorAccent</item>
<item name="tabIndicatorHeight">2dp</item>
<item name="tabPaddingStart">12dp</item>
<item name="tabPaddingEnd">12dp</item>
<item name="tabBackground">?attr/selectableItemBackground</item>
<item name="tabTextAppearance">@style/TextAppearance.Design.Tab</item>
<item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>
Ответ 4
привет, вы можете попробовать это как обходное решение, которое я сделал, следуя: -
1 - создать обычное табло.
2-сделать режим MODE_FIXED
2-добавление его в framellayout и над ним добавляет линейный макет horizonytal.
3-добавить кнопки в горизонтальном макете, как количество ваших вкладок, и сделать кнопки равными размеру layout_wight = 1 для каждой кнопки.
4 - сделайте прозрачные кнопки кнопок.
3-добавить spertator между кнопками в горизонтальной линейной раскладке через представление или anyview и указать widht как 0.5dp или то, что вам нужно.
4 - вы можете добавить yor клики на кнопках или изменить кнопку на любое представление oter, которое не обрабатывает щелчок, поэтому вкладка под ним примет действие click:).
это могут быть уродливые решения, но он отлично работает и выполняет работу
еще одна подсказка, если вы хотите изменить фон выбранной вкладки, вы можете сделать индикатор hieght в стиле tablayout равным фактической высоте табуляции.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/content_parent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="@android:color/transparent" />
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
style="@style/MyCustomTabLayout"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_gravity="bottom"
android:background="#99888888"
android:clickable="false"
android:layoutDirection="rtl"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0.5dp"
android:layout_gravity="bottom"
android:layout_marginBottom="60dp"
android:background="#60ffffff"></LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_gravity="bottom|right"
android:background="@android:color/transparent"
android:orientation="horizontal">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:background="@android:color/transparent"
android:clickable="true" />
<LinearLayout
android:layout_width="0.5dp"
android:layout_height="60dp"
android:background="#60ffffff"></LinearLayout>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:background="@android:color/transparent"
android:clickable="true"
/>
<LinearLayout
android:layout_width="0.5dp"
android:layout_height="60dp"
android:background="#60ffffff"></LinearLayout>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:background="@android:color/transparent"
android:clickable="true"
/>
<LinearLayout
android:layout_width="0.5dp"
android:layout_height="60dp"
android:background="#60ffffff"></LinearLayout>
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:background="@android:color/transparent"
android:clickable="true"
/>
<LinearLayout
android:layout_width="0.5dp"
android:layout_height="60dp"
android:background="#60ffffff"></LinearLayout>
<Button
android:id="@+id/button5"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:background="@android:color/transparent"
android:clickable="true"
/>
</LinearLayout>
</FrameLayout>
и это для стиля
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="tabIndicatorColor">#50000000</item>
<item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item>
<item name="tabIndicatorHeight">60dp</item>
<item name="tabSelectedTextColor">#222222</item>
Ответ 5
попробуйте это, надейтесь, что это сработает для вас.
tab_activity.xml
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@color/edt_footer_bg" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="15dp"
android:background="@android:color/transparent" >
</FrameLayout>
</LinearLayout>
</TabHost>
home_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:mytextview="http://schemas.android.com/apk/res/com.bne"
android:layout_height="50dp"
android:layout_marginRight="2dp"
android:background="@color/app_bg_inner"
android:gravity="center"
android:padding="10dp" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@drawable/tab_selector"
android:textSize="@dimen/txt_12"
mytextview:txt_custom_font="@string/RobotoRegular" />
</LinearLayout>
Ответ 6
Не лучший, но альтернативный способ, который я использовал для текущего.
В Main.Xml
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/Base.Widget.Design.TabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/master_color"
app:elevation="0dp"
app:tabMode="scrollable"
app:tabPaddingEnd="2dp"
app:tabPaddingStart="0dp"
app:tabSelectedTextColor="@color/white"
app:tabTextColor="#82c6e6" />
Я использую фрагмент и делаю в onCreate()
как
if (savedInstanceState == null) {
replaceFragment(fragmentOne);
}
Задать вкладку
private void setupTabLayout() {
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
allTabs.addTab(allTabs.newTab().setText("CURRENT YEAR"), true);
allTabs.addTab(allTabs.newTab().setText("2015"));
allTabs.addTab(allTabs.newTab().setText("2014"));
allTabs.addTab(allTabs.newTab().setText("2013"));
allTabs.addTab(allTabs.newTab().setText("2012"));
allTabs.addTab(allTabs.newTab().setText("2011"));
//Hide Indicator
allTabs.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.transparent));
//Set Custom tab Background
for (int i = 1; i < allTabs.getTabCount(); i++) {
TabLayout.Tab tab = allTabs.getTabAt(i);
RelativeLayout relativeLayout = (RelativeLayout)
LayoutInflater.from(getActivity()).inflate(R.layout.tab_layout, allTabs, false);
tvTabText = (TextView) relativeLayout.findViewById(R.id.tab_title);
View view = (View) relativeLayout.findViewById(R.id.deviderView);
tvTabText.setText(tab.getText());
tab.setCustomView(relativeLayout);
if (i == 0) {
view.setVisibility(View.GONE);
tab.select();
}
}
}
tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Tab title -->
<TextView
android:id="@+id/tab_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:padding="10dp"
android:text="sdasd"
android:textColor="@drawable/tab_item_selector"
android:textSize="@dimen/text_size_normal"
android:textStyle="bold" />
<!-- Tab divider -->
<View
android:id="@+id/deviderView"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:background="@android:color/white"
android:gravity="right" />
</RelativeLayout>
tab_item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="@android:color/white" />
<item android:state_focused="true" android:color="@android:color/white" />
<item android:state_pressed="true" android:color="@android:color/white" />
<item android:color="#82c6e6" />
</selector>
Всегда рассматривайте как необязательный ответ.
Ответ 7
Я не думаю, что это возможно, но если во время создания табуляции вы не указали customView и, например, не добавили свой разделитель; TextView и вы явно TextView.setCompoundDrawablesWithIntrinsicBounds(0, 0,(int)id_of_a_divider, 0);
как вы пытаетесь обнаружить, если его первый Tab
,
if(firstTab){
tabLayout.getTabAt(0).getCustomView()
.setCompoundDrawablesWithIntrinsicBounds(0, 0,(int)id_of_a_divider, 0);
//some little casting
}else if(lastTab){
//dont get any
tabLayout.getTabAt(index).getCustomView()
.setCompoundDrawablesWithIntrinsicBounds(0,0,0, 0);
else{
//the rest takes two sides,
tabLayout.getTabAt(index).getCustomView()
.setCompoundDrawablesWithIntrinsicBounds((int)id_of_a_divider
, 0,(int)id_of_a_divider, 0);
Надеюсь, вы поймете мою идею.
Ответ 8
попробуйте использовать этот код для установки divder
в TabHost
mTabHost.getTabWidget().setDividerDrawable(R.Color.blue);
Ответ 9
Одним из способов добавления пользовательского разделителя является его программное назначение:
tablayout.getTabWidget().setDividerDrawable(R.drawable.yourdivider image name);
Убедитесь, что вы вызываете это, прежде чем устанавливать содержимое вкладок. Это сокрушило бы меня, если бы я позвонил ему.
вы также можете использовать эту строку, если это не работает.
if(Build.VERSION.SDK_INT >= 11)
tablayout.getTabWidget().setShowDividers(TabWidget.SHOW_DIVIDER_MIDDLE);