ViewPager 상단 탐색

14252 단어 android
선생님의 강의에 따라 썼습니다. 선생님의 강의는 2시간밖에 안 걸렸지만 자기가 따라 쓰고 수정하는 데 꼬박 하루가 걸렸습니다. 이 내비게이션을 사용하는 곳이 정말 많습니다. 주석을 쓰고 기록하세요!
1. 주요 사용자 정의 클래스, ViewPagerIndicator는LinearLayout에서 계승
package cq.cake.customview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

import cq.cake.indicator.R;

/**
 * My Application --  cq.cake.customview
 * Created by Small Cake on  2016/3/17 10:45.
 */
public class ViewPagerIndicator extends LinearLayout {
    //     
    private Paint mPaint;
    //      
    private Path mPath;
    //      
    private int mTriangleWidth;

    private int mTriangleHeight;
    //      ,
    private static final float RADIO_TRIANGLE_WIDTH = 1/6F;
    //          
    private final int DIMENSION_TRIANGLE_WIDTH_MAX = (int) (getScreenWidth()/3*RADIO_TRIANGLE_WIDTH);
    //          
    private int mInitTranslationX;
    //      
    private int mTranslationX;

    //     
    private int mTabVisibleCount;
    private static final int COUNT_DEFAULT_TAB  =4;
    private int screenWidth;

    //            
    private List<String> mTitles;
    private static final int COLOR_TEXT_NORMAL = 0X77FFFFFF;
    private static final int COLOR_TEXT_HIGHLIGHT = 0xFFFFFFFF;


    public ViewPagerIndicator(Context context) {
        this(context, null);
    }

    public ViewPagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        //     tab  
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
        mTabVisibleCount  = a.getInt(R.styleable.ViewPagerIndicator_visible_tab_count,COUNT_DEFAULT_TAB);
        if (mTabVisibleCount<0){
            mTabVisibleCount  = COUNT_DEFAULT_TAB;

        }
        //    
        a.recycle();


        //     
        mPaint = new Paint();
        mPaint.setAntiAlias(true);//     
        mPaint.setColor(Color.parseColor("#ffffff"));
        //       
        mPaint.setStyle(Paint.Style.FILL);
        //        ,      3   
        mPaint.setPathEffect(new CornerPathEffect(3));
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {

        canvas.save();
        //  
        canvas.translate(mInitTranslationX + mTranslationX, getHeight() + 2);
        canvas.drawPath(mPath, mPaint);


        canvas.restore();
        super.dispatchDraw(canvas);
    }

    /**
     *                
     *                  
     * @param w
     * @param h
     * @param oldw
     * @param oldh
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //        
        mTriangleWidth = (int) (w/mTabVisibleCount*RADIO_TRIANGLE_WIDTH);

        mTriangleWidth = Math.min(mTriangleWidth,DIMENSION_TRIANGLE_WIDTH_MAX);
        //          
        mInitTranslationX = w/mTabVisibleCount/2-mTriangleWidth/2;
        initTriangle();


    }

    /**
     *  xml          
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        //       
        int cCount = getChildCount();
        if (cCount==0)return;
        for (int i = 0; i < cCount; i++) {
            View view = getChildAt(i);
            LinearLayout.LayoutParams lp = (LayoutParams) view.getLayoutParams();

            lp.weight = 0;
            lp.width = getScreenWidth()/mTabVisibleCount;
            view.setLayoutParams(lp);
        }
        setTabItemClick();
    }

    private void initTriangle() {
        //     
        mTriangleHeight = mTriangleWidth/2;
        mPath  = new Path();
        mPath.moveTo(0, 0);
        mPath.lineTo(mTriangleWidth, 0);
        mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight);
        //     
        mPath.close();
    }

    /**
     *              
     * @param position
     * @param offset
     */

    public void scroll(int position, float offset) {

        int tabWidth = getWidth()/mTabVisibleCount;
        mTranslationX = (int) (tabWidth*(offset+position));

        // tab        
        if (position>=(mTabVisibleCount - 2)&&offset>0&&getChildCount()>mTabVisibleCount){

            if (mTabVisibleCount!=1){
                this.scrollTo(
                        (position-(mTabVisibleCount-2))*tabWidth+(int)(tabWidth*offset)
                        ,0);
            }else{
                this.scrollTo(position*tabWidth+(int)(tabWidth*offset),0);
            }

        }
        //    
        invalidate();

    }

    public int getScreenWidth() {
        WindowManager wm  = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();

        wm.getDefaultDisplay().getMetrics(outMetrics);

        return outMetrics.widthPixels;
    }

    public void setTabItemTitles(List<String> titles) {
        if (titles!=null&&titles.size()>0){
            this.removeAllViews();
            mTitles = titles;
            for (String title:mTitles){
                addView(generateTextView(title));
            }
        }
        setTabItemClick();
    }



    /**
     *      tab   
     * @param count
     */
    public void setVisibleTabCount(int count){
        mTabVisibleCount = count;
    }
    private View generateTextView(String title){
        TextView tv = new TextView(getContext());

        LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
        lp.width = getScreenWidth()/mTabVisibleCount;
        tv.setText(title);
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        tv.setTextColor(COLOR_TEXT_NORMAL);
        tv.setLayoutParams(lp);
        return tv;
    }

    private ViewPager mViewPager;

    /**
     *      ViewPager
     * @param viewPager
     * @param pos
     */
    public void setViewPager(ViewPager viewPager, final int pos){

        mViewPager = viewPager;



        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //positionOffset      
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //tabWidth*positionOffset+positioin*tabWidth//       
                scroll(position, positionOffset);
                if (mListener != null) {
                    mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                if (mListener != null) {
                    mListener.onPageSelected(position);
                }
                heightLightTextView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (mListener != null) {
                    mListener.onPageScrollStateChanged(state);
                }
            }
        });
        mViewPager.setCurrentItem(pos);
        heightLightTextView(pos);
    }

    public interface PageOnChangeListener{
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
        public void onPageSelected(int position);
        public void onPageScrollStateChanged(int state);
    }

    public PageOnChangeListener mListener;
    public void setOnPageChangerListener(PageOnChangeListener listener){
        this.mListener = listener;
    }

    /**
     *       
     */
    private void resetTextViewColor(){

        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (view instanceof TextView){
                ((TextView) view).setTextColor(COLOR_TEXT_NORMAL);
            }
        }
    }

    /**
     *     tab   
     * @param pos
     */
    private void heightLightTextView(int pos){

        resetTextViewColor();
        View view = getChildAt(pos);
        if (view instanceof TextView){
            ((TextView) view).setTextColor(COLOR_TEXT_HIGHLIGHT);
        }
    }

    /**
     *   tab     
     */
    private void setTabItemClick(){
        int cCount = getChildCount();
        for (int i = 0; i < cCount; i++) {
            final int j = i;
            View view = getChildAt(i);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mViewPager.setCurrentItem(j);
                }
            });
        }
    }
}
2.마운트할 Fragment 컨테이너
package cq.cake.customview;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * My Application --  cq.cake.customview
 * Created by Small Cake on  2016/3/17 11:32.
 */
public class VpSimpleFragment extends Fragment {

    private String mTilte;
    private static final String BUNDLE_TITLE = "title";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Bundle bundle = getArguments();
        if (bundle!=null){
            mTilte  =bundle.getString(BUNDLE_TITLE);
        }
        TextView tv = new TextView(getActivity());
        tv.setText(mTilte);
        tv.setGravity(Gravity.CENTER);
        return tv;
    }

    public static VpSimpleFragment newInstance(String title){
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_TITLE,title);
        VpSimpleFragment fragment = new VpSimpleFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
}

3. 전시용 MainActivity
package cq.cake.indicator;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cq.cake.customview.ViewPagerIndicator;
import cq.cake.customview.VpSimpleFragment;

public class MainActivity extends FragmentActivity {

    private ViewPager mViewPager;
    private ViewPagerIndicator mIndicator;

    private List<String> mTitles = Arrays.asList("  1","  2","  3","  4","  5","  6","  7","  8","  9");

    private List<VpSimpleFragment> mContents = new ArrayList<VpSimpleFragment>();

    private FragmentPagerAdapter mAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        
        initView();
        initData();
        mIndicator.setVisibleTabCount(3);

        mIndicator.setTabItemTitles(mTitles);
        mViewPager.setAdapter(mAdapter);

        mIndicator.setViewPager(mViewPager,0);

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //positionOffset      
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //tabWidth*positionOffset+positioin*tabWidth//       
                mIndicator.scroll(position, positionOffset);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    private void initData() {

        for (String title:mTitles){
            VpSimpleFragment  fragment = VpSimpleFragment.newInstance(title);
            mContents.add(fragment);
        }
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mContents.get(position);
            }

            @Override
            public int getCount() {
                return mContents.size();
            }
        };
    }

    private void initView() {
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mIndicator = (ViewPagerIndicator) findViewById(R.id.indicator);
    }
}

4. 홈 페이지의 layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#ffffff"
    xmlns:cake ="http://schemas.android.com/apk/res-auto"
    tools:context="cq.cake.indicator.MainActivity">
    <cq.cake.customview.ViewPagerIndicator
        android:orientation="horizontal"
        android:background="#383737"
        android:id="@+id/indicator"
        android:layout_width="match_parent"
        cake:visible_tab_count="4"
        android:layout_height="45dp">
    </cq.cake.customview.ViewPagerIndicator>

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

코드 중의 주석은 이미 충분히 썼는데, 만약 아직 이해하지 못하는 학우라면!원본 다운로드해서 보실 수 있어요.
소스 주소:ViewPager 슬라이딩 탐색

좋은 웹페이지 즐겨찾기