自定义控件-头部导航栏(仿今日头条)

1.demo简介

本demo实现的是根据屏幕左右滑动实现的实现的字体颜色动态跟踪,主要设计自定义控件的使用以及viewpager的使用

2.逻辑分析

1.实现左右滑动,需要结合viewpager并且设置监听
2.需要结合自定义控件,继承textView
3.自定义控件需要自定义初始颜色值与变化颜色值,以及需要提供对外接口来对字体颜色变换进行控制

3.具体步骤

  • attrs.xml



    
    


  • main_activity.xml(主布局文件)


    
    


  • fragment.xml(碎片布局文件)



    

-ColorTrackTextView.class(自定义控件实现类)

package com.incall.apps.textswitch;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.annotation.Nullable;

@SuppressLint("AppCompatCustomView")
public class ColorTrackTextView extends TextView {

    private Paint mOriginPaint;
    private Paint mChangePaint;
    //设置变色百分比
    private float currentProgress = 0.0f;
    //设置变色朝向
    Direction mdirection = Direction.LEFT_TO_RIGHT;


    public enum Direction {
        LEFT_TO_RIGHT, RIGHT_TO_LEFT;
    }

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

    public ColorTrackTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ColorTrackTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public ColorTrackTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initPaint(context, attrs);
    }

    /**
     * 初始化
     */
    private void initPaint(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ColorTrackTextView);
        int orginColor = array.getColor(R.styleable.ColorTrackTextView_originColor, getTextColors().getDefaultColor());
        int changeColor = array.getColor(R.styleable.ColorTrackTextView_changeColor, getTextColors().getDefaultColor());
        mOriginPaint = getPaintByColor(orginColor);
        mChangePaint = getPaintByColor(changeColor);
        array.recycle();
    }

    /**
     * 根据颜色值获取画笔
     *
     * @return
     */
    private Paint getPaintByColor(int color) {
        Paint paint = new Paint();
        //设置颜色
        paint.setColor(color);
        //抗锯齿
        paint.setAntiAlias(true);
        //防抖动
        paint.setDither(true);
        //设置字体大小
        paint.setTextSize(getTextSize());
        return paint;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int middle = (int) (currentProgress * getWidth());
        //从左变到右
        if (mdirection == Direction.LEFT_TO_RIGHT) {
            drawText(canvas, mOriginPaint, middle, getWidth());
            drawText(canvas, mChangePaint, 0, middle);
        }
        //从右边变到左
        else if (mdirection == Direction.RIGHT_TO_LEFT) {
            drawText(canvas, mOriginPaint, 0, getWidth() - middle);
            drawText(canvas, mChangePaint, getWidth() - middle, getWidth());
        }
    }

    /**
     * * @description 文字图像绘制
     *
     * @param canvas
     * @param paint
     * @param start
     * @param end
     * @return void
     */
    private void drawText(Canvas canvas, Paint paint, int start, int end) {
        canvas.save();
        //根据进度计算中间值
        Rect rect = new Rect(start, 0, end, getHeight());
        canvas.clipRect(rect);
        String text = getText().toString();
        //计算起始位置
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int x = getWidth() / 2 - bounds.width() / 2;
        //计算基线
        Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
        int dy = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;
        int baseLine = getHeight() / 2 + dy;
        canvas.drawText(text, x, baseLine, paint);//初始颜色
        canvas.restore();
    }

    public void setCurrentProgress(float currentProgress) {
        this.currentProgress = currentProgress;
        invalidate();
    }

    //设置变色朝向
    public void setMdirection(Direction mdirection) {
        this.mdirection = mdirection;
    }

    public void setChangeColor(int changeColor) {
        this.mChangePaint.setColor(changeColor);
    }

    public void setOriginColor(int originColor) {
        this.mOriginPaint.setColor(originColor);
    }
}
  • ItemFragment.class(碎片实现类)
package com.incall.apps.textswitch;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class ItemFragment extends Fragment {

    private static final String TITLE = "tile";
    public ItemFragment() {
    }

    public static ItemFragment newInstance(String item) {
        ItemFragment fragment = new ItemFragment();
        Bundle args = new Bundle();
        args.putString(TITLE, item);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item, container, false);
        TextView tv = view.findViewById(R.id.fi_text);
        Bundle bundle = getArguments();
        tv.setText(bundle.getString(TITLE));
        return view;
    }
}
  • ViewPagerActivity.class(主布局类)
package com.incall.apps.textswitch;

import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

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

public class ViewPagerActivity extends AppCompatActivity {
    private String[] item = {"直播", "推荐", "视频", "图片", "段子", "精华"};
    private LinearLayout mLinearLayout;
    private List mColorTrackTextViews;
    private ViewPager mViewPage;

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


    /**
     * 初始化
     */
    private void init() {
        mColorTrackTextViews = new ArrayList<>();
        mLinearLayout = findViewById(R.id.ac_linearLayout);
        mViewPage = findViewById(R.id.ac_viewPager);
        initViewPager();
        initIndicator();


    }


    /**
     * 初始化ViewPager
     */
    private void initViewPager() {
        mViewPage.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return ItemFragment.newInstance(item[position]);
            }

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


            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                super.destroyItem(container, position, object);
            }
        });
        mViewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //position:代表当前位置
                //positionOffset:当前滚动的百分比

                //1.左边文字
                ColorTrackTextView left = mColorTrackTextViews.get(position);
                left.setMdirection(ColorTrackTextView.Direction.RIGHT_TO_LEFT);
                left.setCurrentProgress(1 - positionOffset);

                //2.右边文字
                if (position < item.length - 1) {
                    ColorTrackTextView right = mColorTrackTextViews.get(position + 1);
                    right.setMdirection(ColorTrackTextView.Direction.LEFT_TO_RIGHT);
                    right.setCurrentProgress(positionOffset);
                }

            }

            @Override
            public void onPageSelected(int position) { }

            @Override
            public void onPageScrollStateChanged(int state) {}
        });
    }

    /**
     * 初始化导航栏,构造导航栏子布局
     */
    private void initIndicator() {
        for (int i = 0; i < item.length; i++) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.weight = 1;
            ColorTrackTextView colorTrackTextView = new ColorTrackTextView(this);
            colorTrackTextView.setTextSize(20);
            colorTrackTextView.setChangeColor(Color.RED);
            colorTrackTextView.setText(item[i]);
            colorTrackTextView.setLayoutParams(params);
            mLinearLayout.addView(colorTrackTextView);
            mColorTrackTextViews.add(colorTrackTextView);
        }
    }
}

4.效果图

动态导航栏.gif

你可能感兴趣的:(自定义控件-头部导航栏(仿今日头条))