自定义view之实现文字不同颜色

news/2024/7/7 20:37:13

效果图
这里写图片描述
这里写图片描述
定义属性

 <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);
        }
    }

http://www.niftyadmin.cn/n/3648895.html

相关文章

[Regex]ASP.NET 中的正则表达式-微软速成课程

ASP.NET 中的正则表达式发布日期&#xff1a; 8/17/2004| 更新日期&#xff1a; 8/17/2004速成课程Steven A. Smith适用范围&#xff1a;Microsoft .NET FrameworkMicrosoft ASP.NET正则表达式 API摘要&#xff1a;正则表达式是一种处理文本的有用工具。无论是验证用户输入、搜…

debian交叉编译ide_如何在Debian 10上设置Eclipse Theia Cloud IDE平台

debian交叉编译ide介绍 (Introduction) With developer tools moving to the cloud, adoption of cloud IDE (Integrated Development Environment) platforms is growing. Cloud IDEs are accessible from every type of modern device through web browsers, and they offer …

Android获取手机型号,系统版本,App版本号等信息

MainActivity如下: package cn.testgethandsetinfo; import android.os.Bundle; import android.text.TextUtils; import android.widget.TextView; import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; import android.co…

如何在Ubuntu 18.04上使用PHP在MySQL中实现分页

The author selected the the Apache Software Foundation to receive a donation as part of the Write for DOnations program. 作者选择了Apache软件基金会作为Write for DOnations计划的一部分来接受捐赠。 介绍 (Introduction) Pagination is the concept of constrainin…

自定义view——仿支付宝咻一咻

效果图 这里首先我们我们做一个波波&#xff0c;思路是这样&#xff1a;①设置圆圈的画笔②绘制图片到中心位置&#xff0c;并设置波的大小为图片宽度的一半③hanlder中设置波的半径不断变大&#xff0c;当半径大于画布宽度一半的时候设置半径为图片的宽度一半 public class X…

Android 5.0 权限管理导致的apk安装失败解决方案

在刚5.0出来的时候&#xff0c; 很多apk 在 5.0上会安装失败&#xff0c; 原因其实是&#xff0c; 安装的apk 中的 自定义权限 与 手机上面已经有的app 的自定义权限相同。 问题&#xff1a;当初有做 百度地图的同事就遇到了这个问题&#xff0c; app一直安装失败。需要去掉权限…

如何在CentOS 7上设置Eclipse Theia Cloud IDE平台

介绍 (Introduction) With developer tools moving to the cloud, adoption of cloud IDE (Integrated Development Environment) platforms is growing. Cloud IDEs are accessible from every type of modern device through web browsers, and they offer numerous advantag…

【Zookeeper】使用Curator操作Zookeeper

简介 Curator 是 Apache ZooKeeper 的Java客户端库。 Zookeeper现有常见的Java API如&#xff1a;原生JavaAPI、Curator、ZkClient等。 添加依赖 <dependency><groupId>org.apache.curator</groupId><artifactId>curator-framework</artifactId&…