TabLayout+ViewPager使用自定義的布局氢烘,實現(xiàn)圖文item


首先看一下最終要實現(xiàn)的效果:


TabLayout自定義圖文布局

一般我們使用TabLayout都默認文字布局怀偷,比較單一。為了能靈活應對產(chǎn)品的各種需求播玖,我們必須學會如何來自定義布局椎工。下面讓我們一步步實現(xiàn)上圖效果 :

1.首先使用TabLayout要引入design庫

compile 'com.android.support:appcompat-v7:25.3.0'

2. 接著寫布局文件activity_main
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="mrallright.zjtest.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="53dp"
        android:background="@android:color/white"
        app:tabGravity="fill"
        app:tabIndicatorHeight="0dp"
        app:tabMode="fixed"
        app:theme="@style/Widget.Design.TabLayout" />
</LinearLayout>

3. 定義Fragment (布局僅使用TextView作為演示)
public class PageFragment extends Fragment {
    public static final String ARG_PAGE="ARG_PAGE";
    private int mPage;
    public static PageFragment newInstance(int page){
        Bundle bundle=new Bundle();
        bundle.putInt(ARG_PAGE,page);
        PageFragment pageFragment=new PageFragment();
        pageFragment.setArguments(bundle);
        return pageFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage=getArguments().getInt(ARG_PAGE);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_page,container,false);
        ((TextView)view.findViewById(R.id.tv)).setText("Fragment #"+mPage);
        return view;
    }
}

其中fragment_page.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">
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
4. 接下來重點來了,我們來定義adapter黎棠,自定義 的布局也是在這里添加進去的
public class TabPageAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT=4;
    private String tabTitles[]=new String[]{"首頁","理財","生活","我的"};
    private Context context;
    public TabPageAdapter(FragmentManager fm,Context context) {
        super(fm);
        this.context=context;
    }

    @Override
    public Fragment getItem(int position) {
        return PageFragment.newInstance(position+1);
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }
   //注意=臁!脓斩!這里就是我們自定義的布局tab_item
    public View getCustomView(int position){
        View view= LayoutInflater.from(context).inflate(R.layout.tab_item,null);
        ImageView iv= (ImageView) view.findViewById(R.id.tab_iv);
        TextView tv= (TextView) view.findViewById(R.id.tab_tv);
        switch (position){
            case 0:
         //drawable代碼在文章最后貼出
       iv.setImageDrawable(context.getResources().getDrawable(R.drawable.rb_home_icon_selector));
                tv.setText("首頁");
                break;
            case 1:
                iv.setImageDrawable(context.getResources().getDrawable(R.drawable.rb_finance_icon_selector));
                tv.setText("理財");
                break;
            case 2:
                iv.setImageDrawable(context.getResources().getDrawable(R.drawable.rb_life_icon_selector));
                tv.setText("生活");
                break;
            case 3:
                iv.setImageDrawable(context.getResources().getDrawable(R.drawable.rb_mine_icon_selector));
                tv.setText("我的");
                break;
        }
        return view;
    }
}

tab_item.xml代碼如下(其中需要自定義textcolor木西,代碼會在文章最后貼出)

<?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="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:paddingTop="5dp"
        android:id="@+id/tab_iv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:textColor="@color/textcolor"
        android:paddingTop="5dp"
        android:id="@+id/tab_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="首頁" />
</LinearLayout>

正常我們的adapter會實現(xiàn)getPageTitle方法,在里面設(shè)置標題随静,這樣就實現(xiàn)了純文字的布局八千,代碼如下:

  @Override
   public  CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

但是今天我們要實現(xiàn)的是圖文布局,所以這個方法需要刪除掉

5. 最后MainActivity的中調(diào)用自定義布局
public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private TabPageAdapter tabAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() {
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        tabAdapter = new TabPageAdapter(getSupportFragmentManager(), this);
        viewPager.setAdapter(tabAdapter);
        tabLayout.setupWithViewPager(viewPager);
      
        for (int i = 0; i < 4; i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
           //注意A敲汀A道Α!這里就是添加我們自定義的布局
            tab.setCustomView(tabAdapter.getCustomView(i)); 
          //這里是初始化時重绷,默認item0被選中沸停,setSelected(true)是為了給圖片和文字設(shè)置選中效果,代碼在文章最后貼出
            if (i == 0) {
                ((ImageView) tab.getCustomView().findViewById(R.id.tab_iv)).setSelected(true);
                ((TextView) tab.getCustomView().findViewById(R.id.tab_tv)).setSelected(true);
            }
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ((ImageView) tab.getCustomView().findViewById(R.id.tab_iv)).setSelected(true);
                ((TextView) tab.getCustomView().findViewById(R.id.tab_tv)).setSelected(true);
                viewPager.setCurrentItem(tab.getPosition());
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                ((ImageView) tab.getCustomView().findViewById(R.id.tab_iv)).setSelected(false);
                ((TextView) tab.getCustomView().findViewById(R.id.tab_tv)).setSelected(false);
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

最后貼一下圖片和文字的選擇效果

  • 圖片的效果以rb_home_icon_selector.xml為例,圖片選擇和未選中請自備圖片
<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_selected="false"
          android:drawable="@mipmap/home_hui"/>
    <item android:state_selected="true"
          android:drawable="@mipmap/home_lan"/>
</selector>
  • textcolor.xml(該文件是在res/color文件夾下昭卓,如果沒有color文件夾請自行建立)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorPrimary" android:state_selected="true" />
    <item android:color="@android:color/black" android:state_selected="false" />
</selector>

本文參考:
[Showdy] http://www.reibang.com/p/ed129686f2cc
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0731/3247.html
http://blog.csdn.net/qiao0809/article/details/53506008

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末愤钾,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子候醒,更是在濱河造成了極大的恐慌能颁,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件倒淫,死亡現(xiàn)場離奇詭異伙菊,居然都是意外死亡,警方通過查閱死者的電腦和手機敌土,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門镜硕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人返干,你說我怎么就攤上這事谦疾。” “怎么了犬金?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我晚顷,道長峰伙,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任该默,我火速辦了婚禮瞳氓,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘栓袖。我一直安慰自己匣摘,他們只是感情好,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布裹刮。 她就那樣靜靜地躺著音榜,像睡著了一般。 火紅的嫁衣襯著肌膚如雪捧弃。 梳的紋絲不亂的頭發(fā)上赠叼,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音违霞,去河邊找鬼嘴办。 笑死,一個胖子當著我的面吹牛买鸽,可吹牛的內(nèi)容都是我干的涧郊。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼眼五,長吁一口氣:“原來是場噩夢啊……” “哼妆艘!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起弹砚,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤双仍,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后桌吃,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體朱沃,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年茅诱,在試婚紗的時候發(fā)現(xiàn)自己被綠了逗物。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡瑟俭,死狀恐怖翎卓,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情摆寄,我是刑警寧澤失暴,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布坯门,位于F島的核電站,受9級特大地震影響逗扒,放射性物質(zhì)發(fā)生泄漏古戴。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一矩肩、第九天 我趴在偏房一處隱蔽的房頂上張望现恼。 院中可真熱鬧,春花似錦黍檩、人聲如沸叉袍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽喳逛。三九已至,卻和暖如春肛跌,著一層夾襖步出監(jiān)牢的瞬間艺配,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工衍慎, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留转唉,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓稳捆,卻偏偏與公主長得像赠法,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子乔夯,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,162評論 25 707
  • 內(nèi)容抽屜菜單ListViewWebViewSwitchButton按鈕點贊按鈕進度條TabLayout圖標下拉刷新...
    皇小弟閱讀 46,766評論 22 665
  • 女兒中考完砖织,一直計劃帶著家人去轉(zhuǎn)轉(zhuǎn)。今日得以成行末荐,蘭新高鐵侧纯,第一站蘭州,走起甲脏。
    cfb90f9dbecf閱讀 92評論 0 0
  • 高三上學期眶熬,部隊來學校招空軍飛行員,對自己體質(zhì)還算滿意的我報名參加块请,順利通過初檢娜氏。聽說復檢容易,而且高考成績只要3...
    華百城閱讀 449評論 0 0