1. 程式人生 > >自定義view之實現文字不同顏色

自定義view之實現文字不同顏色

效果圖
這裡寫圖片描述
這裡寫圖片描述
定義屬性

 <declare-styleable name="ColorTrackTextView">
        <attr name="originColor" format="color"/>
        <attr name="changeColor" format="color"/>
    </declare-styleable>

自定義佈局:主要方法是:canvas.clipRect

public class ColorTrackTextView extends TextView {
    private
Paint mOriginPaint; private Paint mChangePaint; //一種文字兩種顏色 private float currentProgress =0; private Direction mDirection = Direction.LEFT_TO_RIGHT; 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) { super(context, attrs, defStyleAttr); initPaint(context, attrs); } public void setOriginColor(int originColor) { mOriginPaint.setColor(originColor); } public
void setChangeColor(int changeColor) { mChangePaint.setColor(changeColor); } public enum Direction { LEFT_TO_RIGHT, RIGHT_TO_LEFT; } private void initPaint(Context context, AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ColorTrackTextView); int originColor = ta.getColor(R.styleable.ColorTrackTextView_originColor, getTextColors().getDefaultColor()); int changeColor = ta.getColor(R.styleable.ColorTrackTextView_changeColor, getTextColors().getDefaultColor()); mOriginPaint = getPaintByColor(originColor); mChangePaint = getPaintByColor(changeColor); ta.recycle(); } 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) { // super.onDraw(canvas); //繪製中間值 int middle = (int) (currentProgress * getWidth()); if (mDirection == Direction.LEFT_TO_RIGHT) {//從左到右繪製,左邊是紅色 drawText(canvas, mChangePaint, 0, middle);//左邊紅色 drawText(canvas, mOriginPaint, middle, getWidth());//右邊藍色 }else{//從右向左繪製,右邊紅色,左邊藍色 drawText(canvas, mChangePaint, getWidth()-middle, getWidth());//右邊紅色 drawText(canvas, mOriginPaint, 0, getWidth()-middle);//左邊藍色 } } public void setCurrentProgress(float currentProgress) { this.currentProgress = currentProgress; invalidate(); } public void setDirection(Direction mDirection) { this.mDirection = mDirection; } /** * 繪製文字 */ private void drawText(Canvas canvas, Paint paint, int startX, int endX) { canvas.save(); //獲取文字 String text = getText().toString(); //對文字進行裁剪 Rect rect = new Rect(startX, 0, endX, getHeight()); canvas.clipRect(rect); paint.getTextBounds(text, 0, text.length(), rect); //獲取寬度 int dx = getWidth() / 2 - rect.width() / 2; //獲取基線 Paint.FontMetrics fontMetrics = paint.getFontMetrics(); int dy = (int) ((fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom); int baseLine = dy + getHeight() / 2; canvas.drawText(text, dx, baseLine, paint); canvas.restore(); } }

主佈局:使用的LinearLayout+viewpager

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

    <LinearLayout
        android:id="@+id/indicator_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingBottom="10dp"
        android:paddingTop="10dp" />

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

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

    <TextView
        android:id="@+id/text_view1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="你好" />
</LinearLayout>

itemFragment的實現

public class ItemFragment extends Fragment {
    public static ItemFragment newInstance(String item) {
        ItemFragment itemFragment = new ItemFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", item);
        itemFragment.setArguments(bundle);
        return itemFragment;
    }

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

        View view = inflater.inflate(R.layout.fragment_item,container,false);

        TextView tv = (TextView) view.findViewById(R.id.text_view1);
        Bundle bundle = getArguments();
        tv.setText(bundle.getString("title"));
        return view;
    }
}

主Activity實現文字顏色的變化

private String[] items = {"直播", "推薦", "視訊", "圖片", "段子", "精華"};
    private LinearLayout mIndicatorContainer;
    private List<ColorTrackTextView> mIndicators;
    private ViewPager mViewPager;
    private String TAG = "ViewPagerActivity";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager);
        mIndicators = new ArrayList<>();
        mIndicatorContainer = (LinearLayout) findViewById(R.id.indicator_view);
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        initIndicator();
        initViewPager();


    }

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

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



            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }


        });


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // 獲取左邊
                ColorTrackTextView left = mIndicators.get(position);
                // 設定朝向
                left.setDirection(ColorTrackTextView.Direction.RIGHT_TO_LEFT);
                // 設定進度  positionOffset 是從 0 一直變化到 1 不信可以看列印
                left.setCurrentProgress(1 - positionOffset);

                // 獲取右邊
                ColorTrackTextView right = mIndicators.get(position + 1);
                right.setDirection(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 < items.length; i++) {
            // 動態新增顏色跟蹤的TextView
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.weight = 1;
            ColorTrackTextView colorTrackTextView = new ColorTrackTextView(this);
            // 設定兩種顏色
            colorTrackTextView.setOriginColor(Color.BLUE);
            colorTrackTextView.setChangeColor(Color.RED);
            colorTrackTextView.setText(items[i]);
            colorTrackTextView.setLayoutParams(params);
            // 把新的加入LinearLayout容器
            mIndicatorContainer.addView(colorTrackTextView);
            // 加入集合
            mIndicators.add(colorTrackTextView);
        }
    }