使用android support library中的tablayout實現頁籤切換效果出現的問題

Tablayout出現以前,因爲google再也不推薦使用tabActivity來實現頁籤切換的效果,或是那種頁籤切換知足不了咱們實際的使用要求,所以出現了第三方的庫:PagerSlidingTabStrip,viewpagerindicator等,使用上很方便;
後來,google官方提供了PagerTabStrip和PagerTitleStrip,效果上仍是不盡如人意,直到最近,推出了design包,包含了tablayout來替代咱們之前自定義的tablayout,而後就有不少人來進行開發,好比:
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0731/3247.html
html


使用很方便,集成也較容易,甚至自定義tab佈局也能夠。java

我此處說的問題以下:android

1.實現效果:
app

這是一個很常見的效果,初步的效果是:每一個頁籤爲自定義的佈局--文字描述居下,圖標居上;切換頁籤時,變換文字便可;ide

2.實現步驟:佈局

  a.佈局文件ui

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_scrollFlags="scroll|enterAlways">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="20sp"
        android:textStyle="bold" />
</android.support.v7.widget.Toolbar>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:fillViewport="true"
            app:tabBackground="@android:color/white"
            app:tabIndicatorColor="@null"
            app:tabMode="fixed"
            app:tabSelectedTextColor="?attr/colorPrimary"
            app:tabTextColor="@android:color/darker_gray"
            android:visibility="visible"/>

    </RelativeLayout>

</LinearLayout>

   b.代碼:this

package com.test.first.tabs;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.test.first.R;

/**
 * MainActivity
 *
 * this is the main page
 *
 * create by gaoxiaohui
 */
public class TabsActivity extends FragmentActivity {

    private final static String TAG = TabsActivity.class.getSimpleName();

    SectionsPagerAdapter mSectionsPagerAdapter;

    private Toolbar toolbar;
    private ViewPager mViewPager;
    private TextView tv_title;
    private TabLayout tabLayout;

    private String[] mTitles = new String[] { "個人設備", "歷史記錄", "我的中心" };
    private int[] imageResId = new int[] { R.drawable.ic_menu_allfriends, R.drawable.ic_menu_emoticons,
        R.drawable.ic_menu_friendslist };

    private String POSITION = "position";

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

    // setToolBarAndTitle(toolbar, R.string.app_name, false, tv_title);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    tv_title = (TextView) findViewById(R.id.tv_title);
    mViewPager = (ViewPager) findViewById(R.id.container);
    final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mViewPager.setAdapter(mSectionsPagerAdapter);

    tabLayout.setupWithViewPager(mViewPager);

    setCustomTablayout(tabLayout);

    }

    /**
     * set custom tab layout
     * 
     * @param tabLayout
     */
    private void setCustomTablayout(final TabLayout tabLayout) {
    for (int i = 0; i < tabLayout.getTabCount(); i++) {
        TabLayout.Tab tab = tabLayout.getTabAt(i);
        if (tab != null) {
        boolean isSelected = tab.isSelected();
        tab.setCustomView(mSectionsPagerAdapter.getTabView(i, isSelected));
        }
    }

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
        mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });
    }

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

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

    public View getTabView(int position, boolean isSelected) {
        View v = LayoutInflater.from(TabsActivity.this).inflate(R.layout.custom_tab, null);
        TextView tv = (TextView) v.findViewById(R.id.textView);
        tv.setText(getPageTitle(position));
        tv.setSelected(isSelected);

        ImageView img = (ImageView) v.findViewById(R.id.imageView);
        img.setImageResource(imageResId[position]);
        img.setSelected(isSelected);
        return v;
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class
        // below).
        switch (position) {
        case 0:
        return BaseFragment.newInstance(getPageTitle(position));
        case 1:
        return BaseFragment.newInstance(getPageTitle(position));
        case 2:
        return BaseFragment.newInstance(getPageTitle(position));
        }
        return null;
    }

    @Override
    public int getCount() {
        // Show mTitles.length total pages.
        return mTitles.length;
    }

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

}

   c.自定義的tabview:google

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

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginTop="2dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="2dp"
        android:textColor="#ffffff"
        android:textSize="14sp" />

</LinearLayout>

  d.BaseFragment:調試

/** 
 * 
 */ 
package com.test.first.tabs; 
 
import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
 
/** 
 * @author King 
 */ 
public class BaseFragment extends Fragment { 
 
    private static final String ARG_PAGE_TITLE = "page_title"; 
 
    /** 
     * Returns a new instance of this fragment for the given section number. 
     */ 
    public static BaseFragment newInstance(CharSequence pageTitle) { 
    BaseFragment fragment = new BaseFragment(); 
    Bundle args = new Bundle(); 
    args.putCharSequence(ARG_PAGE_TITLE, pageTitle); 
    fragment.setArguments(args); 
    return fragment; 
    } 
 
    public BaseFragment() { 
    } 
 
    @Override 
    public void onCreate(@Nullable Bundle savedInstanceState) { 
    // 
    super.onCreate(savedInstanceState); 
 
    } 
 
    @Override 
    @Nullable 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, 
        @Nullable Bundle savedInstanceState) { 
 
    return super.onCreateView(inflater, container, savedInstanceState); 
    } 
 
    @Override 
    public void onPause() { 
    // 
    super.onPause(); 
 
    } 
 
}

  e.相關的圖標暫不考慮;

  如今來講一說問題:

  效果圖1.,打開頁面,默認選中第一個

  效果圖2.,切換到第二個頁籤,兩個都選中

  效果圖3.,切換到第三個頁籤,第一第三個都選中

  效果圖4.,切換會第一個頁籤,正常,而且之後都正常顯示;


  好了,這就是我遇到的問題,但願大神給予幫助。。。


2016-4-18 6:40補充:

問題解決,代碼以下:

/**
 * init the datas and views
 */
private void initDataAndView() {

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mTabPagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), mTitles );

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

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

    initTabIcons(mTabLayout);

}

private void initTabIcons(@NonNull TabLayout tabLayout) {
    for (int i = 0; i < tabLayout.getTabCount(); i++) {
        TabLayout.Tab tab = tabLayout.getTabAt(i);
        if (tab != null) {
            setTabIconByPosition(tab, i);
        }
    }
}

private void setTabIconByPosition(@NonNull TabLayout.Tab tab, int position) {
    switch (position) {
        case 0:
            tab.setIcon(R.drawable.selector_tab_home);
            break;
        case 1:
            tab.setIcon(R.drawable.selector_tab_msg);
            break;
        case 2:
            tab.setIcon(R.drawable.selector_tab_my);
            break;
        default:
            break;
    }
}

另外,發現的另外一個問題是,tablayout高度,一直不是很nice,繼續調試中。。。

相關文章
相關標籤/搜索