Tablayout 标题不出现
Posted
技术标签:
【中文标题】Tablayout 标题不出现【英文标题】:Tablayout Title doesn't appear 【发布时间】:2021-08-31 11:09:05 【问题描述】:我有一个 Tablayout 通过 ViewPager 和适配器显示三个片段,问题是标题没有出现: MainActivity.java:
package com.asd.tab3;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity
TabLayout tb;
ViewPager vp;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tb=findViewById(R.id.tab1);
vp=findViewById(R.id.viwp);
final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(), tb.getTabCount());
vp.setAdapter(adapter);
tb.setupWithViewPager(vp);
MyAdapter.java
package com.asd.tab3;
import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class MyAdapter extends FragmentPagerAdapter
private Context myContext;
int totalTabs;
public MyAdapter(Context context, FragmentManager fm, int totalTabs)
super(fm);
myContext = context;
this.totalTabs = totalTabs;
// this is for fragment tabs
@Override
public Fragment getItem(int position)
switch (position)
case 0:
BlankFragment homeFragment = new BlankFragment();
return homeFragment;
case 1:
BlankFragment2 sportFragment = new BlankFragment2();
return sportFragment;
case 2:
BlankFragment3 movieFragment = new BlankFragment3();
return movieFragment;
default:
return null;
// this counts total number of tabs
@Override
public int getCount()
return totalTabs;
Rem:我的问题和这个帖子不一样:(Titles in TabLayout donsen't appear)
【问题讨论】:
public int getCount() return totalTabs.size(); 【参考方案1】:您应该在 FragmentPageAdapter
类中覆盖方法 getPageTitle()
(在您的情况下为 MyAdapter
)。
* This method may be called by the ViewPager to obtain a title string
* to describe the specified page. This method may return null
* indicating no title for this page. The default implementation returns
* null.
*
* @param position The position of the title requested
* @return A title for the requested page
fun getPageTitle(position: Int): CharSequence?
目前,title 没有出现,因为它使用的是方法的默认实现,总是返回 null。
【讨论】:
【参考方案2】:我通过使用 (getTabAt(index).setText = "Some Text";) 解决了它
tb.getTabAt(0).setText("First");
【讨论】:
以上是关于Tablayout 标题不出现的主要内容,如果未能解决你的问题,请参考以下文章