在 Android Studio 中将图标添加到 TabLayout

Add Icons to TabLayouts in Android Studio

我正在尝试基于 github, with chat21 demo app also in github and the thing is that I want to add Icons to TabLayouts and I am stuck there because I tried a couple times on my own and I just can't get it to work, so here is an image of how I want my chat tabs to look、

上的 chat21 sdk 应用程序为 android 创建一个聊天应用程序

这里是 tab_activity.xml 代码:

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

<android.support.design.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/windowBackground"
tools:context=".TabActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    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:background="@color/colorPrimary"
        android:layout_height="wrap_content"
        app:tabIndicatorColor="@color/white"
        app:tabIndicatorHeight="3dp" />

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

<android.support.v4.view.ViewPager

    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />



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

这里是 java 中的 TabActivity:

package chat21.android.demo;

import android.os.Bundle;
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.support.v7.widget.Toolbar;

import org.chat21.android.core.ChatManager;
import org.chat21.android.ui.ChatUI;

import java.util.HashMap;
import java.util.Map;

public class TabActivity extends AppCompatActivity {
private static final String TAG = TabActivity.class.getName();

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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


    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.view_pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

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

    ChatUI.getInstance().processRemoteNotification(getIntent());
}

@Override
protected void onResume() {
    ChatManager.getInstance().getMyPresenceHandler().connect();
    super.onResume();
}

@Override
protected void onDestroy() {
    ChatManager.getInstance().getMyPresenceHandler().dispose();
    super.onDestroy();
}

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is 
present.
//        getMenuInflater().inflate(R.menu.menu_tab, menu);
//        return true;
//    }
//
//    @Override
    //    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    private int tabsCount;
    private Map<String, Item> tabsMap;
    private String[] tabsTags;

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);

        tabsMap = new HashMap<>();

        // create a map with all tabs
        tabsMap.put(getString(R.string.tag_home),
                new Item(getString(R.string.tab_home_title), 1));
        tabsMap.put(getString(R.string.tag_chat),
                new Item(getString(R.string.tab_chat_title), 1));
        tabsMap.put(getString(R.string.tag_profile),
                new Item(getString(R.string.tab_profile_title), 1));

        // retrieve tab tags
        tabsTags = getResources().getStringArray(R.array.tab_tags);
        tabsCount = tabsTags.length; // count tab tags
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.

        String tabTag = getTagByPosition(position);
        if (tabTag.equals(getString(R.string.tag_home))) {
            return HomeFragment.newInstance();
        } else if (tabTag.equals(getString(R.string.tag_chat))) {
            return ChatFragment.newInstance();
        } else if (tabTag.equals(getString(R.string.tag_profile))) {
            return UserProfileFragment.newInstance();
        } else {
            // default load home
            return ChatFragment.newInstance();
        }
    }

    @Override
    public int getCount() {
        return tabsCount;
    }

    private String getTagByPosition(int position) {
        return tabsTags[position];
    }

    private String getTitleByTag(String tag) {
        return tabsMap.get(tag).getTitle();
    }

    private int getIconByTag(String tag) {
        return tabsMap.get(tag).getIcon();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        String tabTag = getTagByPosition(position);
        return getTitleByTag(tabTag);


    }

    private class Item {
        private String title;
        private int icon;

        private Item(String title, int icon) {
            setTitle(title);
            setIcon(icon);
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getIcon() {
            return icon;
        }

        public void setIcon(int icon) {
            this.icon = icon;
        }

        @Override
        public String toString() {
            return "Item{" +
                    "title='" + title + '\'' +
                    ", icon='" + icon + '\'' +
                    '}';
        }
    }
}
}

我想你正在寻找这个:

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);
    }
}
}

(this is the result)

这是添加图像的代码:

    private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}

如果您想要与图片中的完全相同,请查看此页面: https://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

当时:6。带有图标和文本的自定义选项卡视图

这是我的代码:

package demo.stackowerflow_demos;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
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.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.content.res.AppCompatResources;

public class MainActivity extends AppCompatActivity {

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

        final TabLayout tab = findViewById(R.id.tab);
        final ViewPager pager = findViewById(R.id.pager);
        pager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(), this));
        setupTabWithViewPager(tab, pager, R.layout.tab_layout);
    }

    //tabs
    enum Tab {

        HOME(R.string.tab_home, R.drawable.ic_home),
        CHAT(R.string.tab_chat, R.drawable.ic_chat),
        PROFILE(R.string.tab_profile, R.drawable.ic_profile);

        Tab(@StringRes int title,
            @DrawableRes int icon) {

            this.title = title;
            this.icon = icon;
        }

        final @StringRes
        int title;

        final @DrawableRes
        int icon;

        static final Tab[] VALUES = values();
    }

    //simple interface
    interface IconedTabPagerAdapter {

        CharSequence getPageTitle(int position);

        Drawable getPageIcon(int position);
    }

    //adapter for pager
    static class SectionsPagerAdapter
            extends FragmentPagerAdapter
            implements IconedTabPagerAdapter {

        private final Context mContext;

        public SectionsPagerAdapter(FragmentManager fm,
                                    Context context) {
            super(fm);
            mContext = context;
        }

        @Override
        public Fragment getItem(int position) {

            final Tab tab = Tab.VALUES[position];
            switch (tab) {
                case CHAT:
                    return ChatFragment.newInstance();
                case PROFILE:
                    return UserProfileFragment.newInstance();
                // default load home
                case HOME:
                default:
                    return HomeFragment.newInstance();
            }
        }

        @Override
        public int getCount() {
            return Tab.VALUES.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            final @StringRes int title = Tab.VALUES[position].title;
            return mContext.getString(title);
        }

        @Override
        public Drawable getPageIcon(int position) {
            final @DrawableRes int icon = Tab.VALUES[position].icon;
            return AppCompatResources.getDrawable(mContext, icon);
        }
    }

    static void setupTabWithViewPager(@NonNull TabLayout tabLayout,
                                      @NonNull ViewPager viewPager,
                                      @LayoutRes int tabCustomView) {
        final PagerAdapter adapter = viewPager.getAdapter();
        if (!(adapter instanceof IconedTabPagerAdapter)) {
            tabLayout.setupWithViewPager(viewPager);
            return;
        }
        final IconedTabPagerAdapter iconedAdapter = ((IconedTabPagerAdapter) adapter);
        for (int position = 0; position < adapter.getCount(); position++) {
            final Drawable icon = iconedAdapter.getPageIcon(position);
            final CharSequence title = adapter.getPageTitle(position);
            tabLayout.addTab(tabLayout.newTab()
                    .setCustomView(tabCustomView)
                    .setIcon(icon)
                    .setText(title));
        }
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabBackground="@color/tab_background"
        app:tabIndicatorColor="@color/tab_indicator" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

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">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:orientation="vertical">

        <android.support.v7.widget.AppCompatImageView
            android:id="@android:id/icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@android:id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="true"
            android:textColor="@color/tab_title_color" />

    </LinearLayout>

</RelativeLayout>

结果: