current position:Home>Introduction to TabLayout (com.google.android.material.tabs.TabLayout)
Introduction to TabLayout (com.google.android.material.tabs.TabLayout)
2023-01-25 11:31:23【Someone from Yungu Li】
TabLayout的使用
一、Import of control library
TabLayout是Android support中的一个控件android.support.design.widget.TabLayout,Google在升级了AndroidX之后,将TabLayout迁移到material包下面去了com.google.android.material.tabs.TabLayout,原来的support下面的TabLayout从API 29开始就不再维护了.所以如果项目已经升级了AndroidX,建议直接使用后者.这里开始使用Androidx了,引入如下:
implementation 'com.google.android.material:material:1.2.0-alpha06'
二、基本使用
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewpager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tab" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tabMode="scrollable" />
</androidx.constraintlayout.widget.ConstraintLayout>
The main page layout is oneViewPager和TabLayout
TabFragment.java
public class TabFragment extends Fragment {
public TabFragment(String str) {
Bundle b = new Bundle();
b.putString("key", str);
setArguments(b);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab, container, false);
TextView textView = view.findViewById(R.id.text);
textView.setText(getArguments().getString("key"));
textView.setBackgroundColor(Color.rgb((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
return view;
}
}
TabFragment中就一个TextView,每一个fragment设置不同的label和背景颜色.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<Fragment> fragments = new ArrayList<>();
private String[] titles = new String[]{
"欧冠", "英超", "西甲", "意甲", "德甲", "法甲", "中超", "欧联杯", "皇马", "巴萨", "拜仁", "利物浦"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
TabLayout tabLayout = findViewById(R.id.tab);
ViewPager viewPager = findViewById(R.id.viewpager);
for (int i = 0; i < titles.length; i++) {
fragments.add(new TabFragment(titles[i]));
}
FmPagerAdapter pagerAdapter = new FmPagerAdapter(Arrays.asList(titles), fragments, getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
简单的分3步:
- 找到TabLayout
- 给ViewPager设置adapter
- 设置TabLayout和ViewPagerlinkage between
运行结果:
tabIndicatorFullWidth
Set the width of the indicator line to match the width of the text,那么就可以设置tabIndicatorFullWidth属性为false,默认为true
tabRippleColor
点击每一个tab的时候,会出现渐变的背景色
设置 app:tabRippleColor=“@color/green”
如果想要去掉这个点击时的背景,可以通过设置tabRippleColorThe property value is a transparent background color
tabTextAppearance
TabLayout并没有直接设置字体大小样式的属性,这时候就可以通过设置自定义属性tabTextAppearance来实现 app:tabTextAppearance=“@style/TextStyle”
<style name="TextStyle">
<item name="android:textSize">20sp</item>
<item name="android:textStyle">bold</item>
</style>
tabIndicatorHeight
这个属性设置指示器的高度,如果我们不需要显示指示器,则可以通过设置tabIndicatorHeight等于0来实现
tabIndicatorGravity
这个属性可以设置指示器的显示位置,可选值有bottom(默认)、center、top、stretch
stretch
app:tabBackground
改变整个TabLayout的颜色,直接在xml中设置:app:tabBackground=“@color/blue”.
app:tabContentStart
TabLayoutThe offset at which the text content in ,自由scrollable时候有效
The system default font starts with 16dp,The second row of labels is Settingsapp:tabContentStart="16dp"以后的情况
tabPaddingStart和tabPaddingEnd
当tabmode 是fix时候,解决tabThe font becomes smaller when the font is squeezed
Set the following two lines of code,问题就解决了:亲测有效;
app:tabPaddingEnd="0dp"
app:tabPaddingStart="0dp"
You can realize the message red dot by defining the layout yourself
自定义layout的item_red_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textAppearance="@style/tab_normal_style"
android:textSize="17sp" />
<View
android:layout_width="8dp"
android:layout_height="8dp"
android:layout_gravity="end|top"
android:background="@color/colorAccent" />
</FrameLayout>
java代码
public class RedDotActivity extends AppCompatActivity {
private ArrayList<Fragment> fragments = new ArrayList<>();
private String[] titles = new String[]{
"欧冠", "英超", "西甲", "意甲", "德甲", "法甲", "中超", "欧联杯", "皇马", "巴萨", "拜仁", "利物浦"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
TabLayout tabLayout = findViewById(R.id.tab);
ViewPager viewPager = findViewById(R.id.viewpager);
for (int i = 0; i < titles.length; i++) {
tabLayout.addTab(tabLayout.newTab().setCustomView(R.layout.item_red_dot));
fragments.add(new TabFragment(titles[i]));
}
for (int i = 0; i < titles.length; i++) {
TextView view = tabLayout.getTabAt(i).getCustomView().findViewById(R.id.text1);
view.setText(titles[i]);
}
FmPagerAdapter pagerAdapter = new FmPagerAdapter(Arrays.asList(titles), fragments, getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
View customView = tab.getCustomView();
if (customView == null) {
tab.setCustomView(R.layout.item_red_dot);
}
TextView textView = tab.getCustomView().findViewById(R.id.text1);
textView.setTextAppearance(RedDotActivity.this, R.style.tab_select_style);
viewPager.setCurrentItem(tab.getPosition(),true);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
View customView = tab.getCustomView();
if (customView == null) {
tab.setCustomView(R.layout.item_red_dot);
}
TextView textView = tab.getCustomView().findViewById(R.id.text1);
textView.setTextAppearance(RedDotActivity.this, R.style.tab_normal_style);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
tabLayout.setScrollPosition(position, positionOffset, true, true);
}
@Override
public void onPageSelected(int position) {
tabLayout.getTabAt(position).select();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
style内容
<style name="tab_normal_style">
<item name="android:textSize">15sp</item>
<item name="android:textStyle">normal</item>
<item name="android:textColor">@color/black</item>
</style>
<style name="tab_select_style">
<item name="android:textSize">17sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@color/green</item>
</style>
copyright notice
author[Someone from Yungu Li],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2023/025/202301251120395334.html
The sidebar is recommended
- The front end of actual combat: copy write millet's official website on the first day
- 1. Linux application programming and network programming---file IO notes in Linux system
- [Front-end notes - CSS] 10. Cascading and inheritance + selector
- 8. Linux application programming and network programming---Linux network programming notes
- [Java|golang] 1828. Count the number of points in a circle
- [Front-end notes——CSS] 11. Box model + background and border
- C + + large Numbers together, according to a combined
- 3. Linux application programming and network programming --- get system information notes
- The use and principle of Kafka message queue
- 5. Linux application programming and network programming---signal notes in Linux
guess what you like
6 · Linux application programming and system programming - senior IO notes
Java collection common interview questions (4)
072-JAVA project training: Imitation QQ instant messaging software series lecture 7 (explaining the realization of the chat interface and functions)
Coordination center performance comparison: how zookeeper solves the load balancing problem
070-JAVA project training: imitation QQ instant messaging software series lecture five (explain user registration function)
Ubuntu installation and configuration (brief)
073-JAVA project training: imitation QQ instant messaging software series lecture eight (explain query and add friend function)
SQL injection classification and error injection EXP
All basic commands in linux fail, showing that the command cannot be found
4. Linux application programming and network programming---Linux process full solution notes (difference between process and program)
Random recommended
- Linux system - basic IO
- Hanlp's understanding of user-defined dictionaries (java version)
- Brief description and configuration of Maven
- 071-JAVA project training: imitation QQ instant messaging software series lecture six (explaining the function of QQ main interface)
- 【Maximum LeetCode】January Algorithm Training (12) Linked List
- 【Max LeetCode】January Algorithm Training (13) Doubly Linked List
- [Big Data Management] Java implements Bloom filter
- [Maximum LeetCode] Algorithm training in January (14) stack
- [Machine Learning] Adaboost Integrated Algorithm
- [Big Data Management] Java implements cuckoo filter (CF)
- Chaozhou Xiangqiao: "Charming Ancient City, Cultural Sharing" Spring Festival Intangible Cultural Heritage Market Opens
- [Big data management] Java realizes the dictionary tree TireTree
- [Max LeetCode] January Algorithm Training (11) Matrix
- New Express (Web framework based on HTTP module encapsulation NodeJS)
- JavaScript error-prone questions (stack processing, call function, prototype chain questions)
- Space "travel", lion and crane dance, intangible cultural heritage experience...During the Spring Festival, Zhuhai Jinwan is so fun!
- Wine 8.0 official release: better support for running Windows applications on Linux and other systems
- Zhongke Sugon: Sugon's new computer "participates in" "The Wandering Earth 2"
- Linux actual combat notes finishing (1.24)
- Winter Vacation JavaScript Tutorial Chapter 1 Variable Promotion
- Automatically execute the specified sql when the springBoot project starts
- Winter vacation javascript cram school Chapter 2 let & const temporary dead zone
- Microsoft CEO Nadella: We firmly believe that the wave of artificial intelligence is unstoppable
- [Bi She] Style Migration Based on CycleGAN [3] Code Migration to Server (Linux) and Environment Construction
- Axiba HTML
- Explore the vachar, test, longtext storage limits of the database mysql
- Web front-end development technology: Web front-end development technology
- Python data structure implements various sorting algorithms (including algorithm introduction and stability, complexity summary)
- Web front-end development technology: Vue routing
- 【 MySQL 】 the seventh part of the process control function
- Web front-end development technology: Vuex state management
- Important concepts and installation of Linux + vim common operations
- [MySQL] Part 9 MySQL Information Functions
- [MySQL] Part VIII Encryption and Decryption Functions
- PAT 1014 Sherlock Holmes' appointment (C++ implementation)
- Android gradle custom plug-in implementation
- Python numpy ValueError: setting an array element with a sequence.
- On Spring notes (annotation-based development)
- Ubuntu18.04 install Hadoop
- Android proguard code obfuscation and decompilation tool