Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> PagerTabStrip及自定義的PagerTab,pagertab

PagerTabStrip及自定義的PagerTab,pagertab

編輯:關於android開發

PagerTabStrip及自定義的PagerTab,pagertab


如圖是效果圖

    

開發中經常會用到上面是一個Tab下面是一個ViewPager(ViewPager再包含幾個Fragment),當點擊Tab或是滑動ViewPager,Tab及ViewPager都會發生對應的變化

如圖我實現的上面一個Tab是自己定義的布局讓其繼承HorizontalScrollView,下面一個使用系統PagerTabStrip很簡單,

當然引用別人的框架Android-ViewPagerIndicator(https://github.com/JakeWharton/ViewPagerIndicator)實現更簡單

如下是主要代碼

package com.it.hello.activity.assets;

import java.util.ArrayList;
import com.it.hello.R;
import com.it.hello.activity.entity.ChannelItem;
import com.it.hello.activity.fragment.FourFragment;
import com.it.hello.activity.fragment.MThreeFragment;
import com.it.hello.activity.fragment.OneFragment;
import com.it.hello.activity.myfragment.MyFragmentOne;
import com.it.hello.activity.myfragment.MyFragmentTwo;
import com.it.hello.activity.util.DensityUtils;
import com.it.hello.activity.widget.ColumnHorizontalScrollView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

/**
 * PagerTabStrip實現ViewPager的滑動
 * @author zh
 *
 */
public class MyStripActivity extends FragmentActivity {

    private ViewPager mViewPager;
    private PagerTabStrip pager_tab_strip;

    /** 自定義的HorizontalScrollView */
    private ColumnHorizontalScrollView mColumnHorizontalScrollView;
    private LinearLayout mRadioGroup_content;
    /** 用戶選擇的分類列表 */
    private ArrayList<ChannelItem> userChannelItems = new ArrayList<ChannelItem>();
    /** 當前選中的欄目 */
    private int columnSelectIndex = 0;
    /** 屏幕的寬度 */
    private int mScreeWidth = 0;
    /** Item寬度 */
    private int mItemWidth = 0;
    private View view;

    @Override
    protected void onCreate(Bundle arg0) {
        // TODO Auto-generated method stub
        super.onCreate(arg0);
        setContentView(R.layout.activity_strip);
        mScreeWidth = DensityUtils.getWindowsWidth(this);
        mItemWidth = mScreeWidth / 3; // 一個Item寬度為屏幕的3分之一
        mViewPager = (ViewPager) findViewById(R.id.vp);
        pager_tab_strip = (PagerTabStrip) findViewById(R.id.pager_tab_strip);
        // 設置標簽下劃線的顏色
        mColumnHorizontalScrollView = (ColumnHorizontalScrollView) findViewById(R.id.mColumnHorizontal);
        mRadioGroup_content = (LinearLayout) findViewById(R.id.mRadioGroup);
        
        initColumData();
        //取消Tab 下面的長橫線
        pager_tab_strip.setDrawFullUnderline(false);
        //改變Tab線的顏色
        pager_tab_strip.setTabIndicatorColor(getResources().getColor(
                R.color.indecolor));
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(new MainAdapter(getSupportFragmentManager()));
    }

    private void initColumData() {
        // TODO Auto-generated method stub
        userChannelItems = new ArrayList<ChannelItem>();
        ChannelItem item = new ChannelItem(0, "標簽0", 0, 0);
        ChannelItem item1 = new ChannelItem(0, "標簽1", 0, 0);
        ChannelItem item2 = new ChannelItem(0, "標簽2", 0, 0);
        ChannelItem item3 = new ChannelItem(0, "標簽3", 0, 0);
        ChannelItem item4 = new ChannelItem(0, "標簽4", 0, 0);
        userChannelItems.add(item);
        userChannelItems.add(item1);
        userChannelItems.add(item2);
        userChannelItems.add(item3);
        userChannelItems.add(item4);

        initTabColumn();

        /**
         * ViewPager切換監聽的方法
         */
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

                    @Override
                    public void onPageSelected(int position) {
                        // TODO Auto-generated method stub
                        mViewPager.setCurrentItem(position);
                        selectTab(position);
                        initColumData();
                    }

                });
    }

    /**
     * 初始化TabColumn欄目項
     */
    private void initTabColumn() {
        // TODO Auto-generated method stub
        mRadioGroup_content.removeAllViews();
        int count = userChannelItems.size();
        mColumnHorizontalScrollView.setParam(this, mScreeWidth,
                mRadioGroup_content);
        for (int i = 0; i < count; i++) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    mItemWidth, LayoutParams.WRAP_CONTENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
            view = View.inflate(this, R.layout.item_mytab, null);
            TextView tv = (TextView) view.findViewById(R.id.tab_title);
            View line = (View) view.findViewById(R.id.tab_line);
            tv.setId(i);
            tv.setText(userChannelItems.get(i).getName());
            if (columnSelectIndex == i) {
                tv.setSelected(true);
                line.setSelected(true);
            }
            view.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
                        View localView = mRadioGroup_content.getChildAt(i);
                        if (localView != arg0) {
                            localView.setSelected(false);
                        } else {
                            localView.setSelected(true);
                            mViewPager.setCurrentItem(i);
                        }
                    }
                }
            });
            mRadioGroup_content.addView(view, i, params);
        }
    }

    /**
     * 選擇的Column裡面的Tab
     * */
    private void selectTab(int tab_postion) {
        columnSelectIndex = tab_postion;
        for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
            View checkView = mRadioGroup_content.getChildAt(tab_postion);
            int k = checkView.getMeasuredWidth();
            int l = checkView.getLeft();
            int i2 = l + k / 2 - mScreeWidth / 2;
            mColumnHorizontalScrollView.smoothScrollTo(i2, 0);
        }
        // 判斷是否選中
        for (int j = 0; j < mRadioGroup_content.getChildCount(); j++) {
            View checkView = mRadioGroup_content.getChildAt(j);
            boolean ischeck;
            if (j == tab_postion) {
                ischeck = true;
            } else {
                ischeck = false;
            }
            checkView.setSelected(ischeck);
        }
    }
    
    /**
     * ViewPager的適配器
     * @author zh
     *
     */
    private class MainAdapter extends FragmentStatePagerAdapter {

        public MainAdapter(FragmentManager fm) {
            super(fm);
            // TODO Auto-generated constructor stub
        }

        // 每個條目返回的Fragment
        @Override
        public Fragment getItem(int position) {
            // TODO Auto-generated method stub
            return createFragment(position);
        }

        // 一共多少個條目
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return 5;
        }

        // 返回每個條目的標題
        @Override
        public CharSequence getPageTitle(int position) {
            return "標簽" + position;
        }
    }
    //private static Map<Integer, Fragment> mFragmentMap = new HashMap<Integer, Fragment>();
    private static SparseArray<Fragment> mFragmentMap = new SparseArray<Fragment>();
    public Fragment createFragment(int position) {
        // TODO Auto-generated method stub
        Fragment fragment = null;
        fragment = mFragmentMap.get(position);//在集合中去除Fragment
        if(fragment == null){//如果沒在集合中取出來  需要重新創建            
            if (position == 0) {
                fragment = new MyFragmentOne();
            } else if (position == 1) {
                fragment = new MyFragmentTwo();
            } else if (position == 3) {
                fragment = new MThreeFragment();
            } else if (position == 4) {
                fragment = new FourFragment();
            } else {
                fragment = new OneFragment();
            }
            if(fragment != null){
                mFragmentMap.put(position, fragment);//把創建好的Fragment存放到集合中緩存起來
            }
        }
        return fragment;
    }
}

布局代碼

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

    <com.it.hello.activity.widget.ColumnHorizontalScrollView
        android:id="@+id/mColumnHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="none" >

        <LinearLayout
            android:id="@+id/mRadioGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#333"
            android:gravity="center_vertical"
            android:orientation="horizontal" />
    </com.it.hello.activity.widget.ColumnHorizontalScrollView>

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

        <android.support.v4.view.PagerTabStrip
            android:id="@+id/pager_tab_strip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#ffffff"
            android:paddingBottom="4dp"
            android:paddingTop="4dp"
            android:textColor="#000" />
    </android.support.v4.view.ViewPager>

</LinearLayout>

自定義的ColumnHorizontalScrollView

package com.it.hello.activity.widget;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.HorizontalScrollView;

public class ColumnHorizontalScrollView extends HorizontalScrollView {
    /** 傳入整體布局 */
    private View ll_content;
    /** 傳入拖動欄布 */
    // private View rl_column;
    /** 屏幕寬度 */
    private int mScreenWitdh = 0;
    /** 父類的活動activity */
    private Activity activity;

    public ColumnHorizontalScrollView(Context context) {
        super(context);
    }

    public ColumnHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ColumnHorizontalScrollView(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 在拖動的時
     * */
    // @Override
    // protected void onScrollChanged(int paramInt1, int paramInt2, int
    // paramInt3, int paramInt4) {
    // super.onScrollChanged(paramInt1, paramInt2, paramInt3, paramInt4);
    // //shade_ShowOrHide();
    // if(!activity.isFinishing() && ll_content !=null){
    // }else{
    // return;
    // }
    // if(paramInt1 ==0){
    // return;
    // }
    // if(ll_content.getWidth() - paramInt1 + rl_column.getLeft() ==
    // mScreenWitdh){
    // return;
    // }
    // }
    /**
     * 傳入父類布局中的資源文件
     * */
    public void setParam(Activity activity, int mScreenWitdh, View paramView1) {
        this.activity = activity;
        this.mScreenWitdh = mScreenWitdh;
        this.ll_content = paramView1;
    }

    /**
     * 判斷左右陰影的顯示隱藏效
     * */
    public void shade_ShowOrHide() {
        if (!activity.isFinishing() && ll_content != null) {
            measure(0, 0);
            // 如果整體寬度小於屏幕寬度的話,那左右陰影都隱藏
            if (mScreenWitdh >= getMeasuredWidth()) {
                // leftImage.setVisibility(View.GONE);
                // rightImage.setVisibility(View.GONE);
            }
        } else {
            return;
        }
        // 如果滑動在最左邊時,左邊陰影隱藏,右邊顯示
        if (getLeft() == 0) {
            // leftImage.setVisibility(View.GONE);
            // rightImage.setVisibility(View.VISIBLE);
            return;
        }
        // 如果滑動在最右邊時,左邊陰影顯示,右邊隱藏
        if (getRight() == getMeasuredWidth() - mScreenWitdh) {
            // leftImage.setVisibility(View.VISIBLE);
            // rightImage.setVisibility(View.GONE);
            return;
        }
        // 否則,說明在中間位置,左、右陰影都顯示
        // leftImage.setVisibility(View.VISIBLE);
        // rightImage.setVisibility(View.VISIBLE);
    }
}
/**獲取屏幕的寬*/
    public final static int getWindowsWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved