【问题标题】:Add Icons+Text to TabLayout将图标+文本添加到 TabLayout
【发布时间】:2016-10-16 10:53:52
【问题描述】:

我正在一个包含三个选项卡的屏幕上工作 这是我的代码。

public class HomeScreen extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private Toolbar toolbar;
private ViewPager pager;
private ViewPagerAdapter adapter;
private SlidingTabLayout tabs;
private CharSequence Titles[] = {"News", "Most Views", "Chart"};
int Numboftabs = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //MAhmoud Code Addtion
    // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
   // getSupportActionBar().setIcon(R.drawable.ic_launcher);

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles
    // fot the Tabs and Number Of Tabs.
    adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles,
            Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true);
    tabs.setViewPager(pager);

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}}

ViewPagerAdapter

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

CharSequence Titles[];
int NumbOfTabs;

public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[],
        int mNumbOfTabsumb) {
    super(fm);
    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;
}
// This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {
    switch (position) {
    case 0:
        return new Tap1();

    case 1:
        return new Tap2();
    case 2:
        return new Tap3();
    }
    return null;
}
// This method return the titles for the Tabs in the Tab Strip
@Override
public CharSequence getPageTitle(int position) {
    return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
@Override
public int getCount() {
    return NumbOfTabs;
}}

【问题讨论】:

    标签: android android-layout material-design android-tabs android-tablayout


    【解决方案1】:

    试试这个方法,这正是你要找的

    http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

    public class MainActivity extends AppCompatActivity {
    
        private Toolbar toolbar;
        private TabLayout tabLayout;
        private ViewPager viewPager;
        private int[] tabIcons = {
                R.drawable.ic_tab_favourite,
                R.drawable.ic_tab_call,
                R.drawable.ic_tab_contacts
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            viewPager = (ViewPager) findViewById(R.id.viewpager);
            setupViewPager(viewPager);
    
            tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(viewPager);
            setupTabIcons();
        }
    
        private void setupTabIcons() {
            tabLayout.getTabAt(0).setIcon(tabIcons[0]);
            tabLayout.getTabAt(1).setIcon(tabIcons[1]);
            tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        }
    
        private void setupViewPager(ViewPager viewPager) {
            ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
            adapter.addFrag(new OneFragment(), "ONE");
            adapter.addFrag(new TwoFragment(), "TWO");
            adapter.addFrag(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 addFrag(Fragment fragment, String title) {
                mFragmentList.add(fragment);
                mFragmentTitleList.add(title);
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                return mFragmentTitleList.get(position);
            }
        }
    }
    

    【讨论】:

    • 我也做过同样的事情,但不知道为什么图像在文本上方但不相邻。可能是什么原因?
    • 您可以在布局 XML 中为每个 TabItem 设置 icon 属性。布局编辑器甚至会向您展示它的外观!但是,当然,然后您实际运行您的应用程序,并且......没有!再次感谢 Android SDK。我喜欢在每次击键后都必须搜索 SO。
    • @rajat44, app:tabInlineLabel="true" 为您的 TabLayout xml 视图解决问题
    【解决方案2】:

    首先创建一个布局 xml 文件,该文件具有您想要的选项卡结构 例如,文本顶部的简单图标。像这样:

    1。创建导航选项卡布局 xml:在 layout 文件夹 > nav_tab.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/nav_tab"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center_horizontal">
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="@dimen/nav_icon"
            android:scaleType="centerInside"
            android:id="@+id/nav_icon"
            android:layout_marginBottom="@dimen/tiny_padding"/>
    
        <TextView
            android:id="@+id/nav_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@string/font_fontFamily_medium"
            android:shadowColor="@android:color/black"
            android:textColor="@color/dark_grey"
            android:textSize="@dimen/nav_tab_label_font_size"
            tools:text="@string/nav_home" />
    
    </LinearLayout>
    

    给你的布局和 id 以膨胀,并给 ImageViewTextView id 以在膨胀父布局后参考。


    2。在drawable 文件夹中定义您的图标,在strings.xml 文件中定义标签

    并按照您希望图标出现的顺序通过它们的资源 id 在数组中引用它们:

    private int[] navIcons = {
            R.drawable.ico_home,
            R.drawable.ico_search,
            R.drawable.ico_notification,
            R.drawable.ico_profile
    };
    private int[] navLabels = {
            R.string.nav_home,
            R.string.nav_search,
            R.string.nav_notifications,
            R.string.nav_profile
    };
    // another resouces array for active state for the icon
    private int[] navIconsActive = {
            R.drawable.ico_home_red,
            R.drawable.ico_search_red,
            R.drawable.ico_notification_red,
            R.drawable.ico_profile_red
    };
    

    3。使用您的ViewerPager 设置您的TabLayout

    TabLayout navigation = (TabLayout) findViewById(R.id.navigation);
    navigation.setupWithViewPager(mainView/* the viewer pager object*/);
    

    现在自定义部分:

    // loop through all navigation tabs
    for (int i = 0; i < navigation.getTabCount(); i++) {
        // inflate the Parent LinearLayout Container for the tab
        // from the layout nav_tab.xml file that we created 'R.layout.nav_tab
        LinearLayout tab = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.nav_tab, null);
    
        // get child TextView and ImageView from this layout for the icon and label
        TextView tab_label = (TextView) tab.findViewById(R.id.nav_label);
        ImageView tab_icon = (ImageView) tab.findViewById(R.id.nav_icon);
    
        // set the label text by getting the actual string value by its id
        // by getting the actual resource value `getResources().getString(string_id)`
        tab_label.setText(getResources().getString(navLabels[i]));
    
        // set the home to be active at first
        if(i == 0) {
            tab_label.setTextColor(getResources().getColor(R.color.efent_color));
            tab_icon.setImageResource(navIconsActive[i]);
        } else {
            tab_icon.setImageResource(navIcons[i]);
        }
    
        // finally publish this custom view to navigation tab
        navigation.getTabAt(i).setCustomView(tab);
    }
    

    ---

    最终触摸设置激活状态并在选择选项卡时更改图标和文本颜色:

    你可以在这里继续我的回答

    change image and color of the text to the tab when selected

    这将实现:

    【讨论】:

    • 如果有人遇到标签布局的高度问题,我们可以通过使用LinearLayout tab 获取膨胀布局的高度来动态设置它ViewTreeObserver 参考这个link 并设置高度使用this动态标签布局
    • 如果您遇到tab.getCustomView() 给出空指针异常的问题,请参考此内容,请尝试this
    • 感谢navigation.getTabAt(i).setCustomView(tab);。我用newTab() 创建了新标签而不是替换现有标签,这是我的错误。
    • @ReejeshPK,你能提供一个TabLayout高度的解决方案吗?我试了很多次都没有成功。
    • @CoolMind 你的 Tab 布局高度太短了吗?
    【解决方案3】:

    如果您想将图标和文本放在 tablayout 中的一行中,您必须进行如下自定义布局。

    custom_tab_heading.xml

    <?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:orientation="vertical"
        android:gravity="center">
        <TextView
            android:id="@+id/tabContent"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textAlignment="center"
            android:textColor="@android:color/black"
            android:gravity="center"/>
    </LinearLayout>
    

    在您的 java 端,您可以编写以下代码来将图像和标题放到您的选项卡中。

    val tabTitles = arrayListOf<String>("  Text Jokes","  Funny Images")
    val tabIcons = arrayListOf<Int>(R.drawable.text_jokes,R.drawable.image_jokes)
    
    
    val tabLinearLayout = LayoutInflater.from(context).inflate(R.layout.custom_tab_heading, null) as LinearLayout
    val tabContent = tabLinearLayout.findViewById<View>(R.id.tabContent) as TextView
    tabContent.text = tabTitles.get(0)
    tabContent.setCompoundDrawablesWithIntrinsicBounds(tabIcons[0], 0, 0, 0)
    myTabLayout.getTabAt(0)!!.setCustomView(tabContent)
    
    val tabLinearLayout1 = LayoutInflater.from(context).inflate(R.layout.custom_tab_heading, null) as LinearLayout
    val tabContent1 = tabLinearLayout1.findViewById<View>(R.id.tabContent) as TextView
    tabContent1.text = tabTitles.get(1)
    tabContent1.setCompoundDrawablesWithIntrinsicBounds(tabIcons[1], 0, 0, 0)
    var l = tabLinearLayout1.layoutParams
    myTabLayout.getTabAt(1)!!.setCustomView(tabContent1)
    

    注意:- 在 tabTitles 数组中,请注意我在文本之前给出了一个空格(&lt;space&gt;Title 1),因为它会在您的图像和标题之间保留空间。

    抱歉,我在这里提供了 kotlin 代码,但您可以轻松地将其转换为 java。如果有人遇到问题,请在此答案中发表评论,我会尽力帮助他们。

    【讨论】:

      【解决方案4】:

      我的好伙伴提到的所有答案当然都是有效的,但是由于ViewPager2 已经存在,因此最好发布相应的解决方案。

      private ViewPager2 viewPager2;
      private TabLayout tablayout;
      
      
      
      private void tabLayoutValueSetter(){
          viewPager2 = findViewById(R.id.viewPager2);
          tablayout = findViewById(R.id.TabLayout);
      
      
          final String[] tabTitles = {"Tab One", "Tab Two", "Tab Three"};//put titles based on your need
          final int[] tabIcons = {R.drawable.icon_1, R.drawable.icon_2, R.drawable.icon_13};
      
          
           TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2,
                  ((tab, position) -> {
                      tab.setText(tabTitles[position]);
                      tab.setIcon(tabIcons[position]);
                  }
                  ));
            tabLayoutMediator.attach();
            //and whereever you want you can detach it (tabLayoutMediator.detach())
      
       }
      

      结果是一个 Tablayout,下面有三个图标和标题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-08
        • 2014-06-21
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-11
        相关资源
        最近更新 更多