本文实例为大家分享了Android自定义view绘制表格的具体代码,供大家参考,具体内容如下

先上效果图

平时很少有这样的表格需求,不过第一想法就是自定义view绘制表格,事实上我确实是用的canvas来绘制的,整个过程看似复杂,实为简单,计算好各个点的坐标后事情就完成一半了。不废话show code

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.robot.common.entity.ScenicDetailInfo;
import com.robot.common.utils.PixelUtil;

/**
 * 景区详情门票信息表格
 *
 * @author ly
 * date 2019/8/12 10:24
 */
public class TicketInfoView extends View {

    private Paint pLine, pText;
    //表格宽高
    private int w, h;
    //每一行的高度
    private int rowH;
    //表格线的宽度
    private float tableLineW;
    //竖线x坐标
    private float vLine1x, vLine2x, vLine3x, vLine4x;
    //横线y坐标
    private float hLine1y, hLine2y;
    //每一列文字的x坐标(单列内居中)
    private float textX1, textX2, textX3, textX4, textX5, textXEnd;
    private static final String text1 = "市场价";
    private static final String text2 = "单人出行";
    private static final String text3 = "多人出行";
    private static final String text4 = "持卡者";
    private static final String text5 = "同行者";
    private static final String text6 = "出行总人数";
    private ScenicDetailInfo.TicketInfo ticketInfo;

    private int tableLineColor = Color.parseColor("#FFB6B4C8");
    private int textColorBlack = Color.parseColor("#FF232627");
    private int textColorGray = Color.parseColor("#FF65657e");
    private int textColorRed = Color.parseColor("#FFfa496a");
    private int blackTextSize = PixelUtil.sp2px(14);
    private int grayTextSize = PixelUtil.sp2px(12);
    private int redTextSize = PixelUtil.sp2px(13);

    //表格上半部分颜色
    private int tableBgColorTop = Color.parseColor("#FFF6F5FF");
    //表格下半部分颜色
    private int tableBgColorBottom = Color.parseColor("#FFE9EAFF");
    //表格高亮部分颜色
    private int tableBgColorHighLight = Color.parseColor("#FF6066DD");

    //三个有颜色的矩形区域
    private RectF topRect, bottomRect, highLightRect;
    private static final int radius = PixelUtil.dp2px(10);
    //圆角矩形的Path
    private Path pathRoundRect;
    //顶部矩形的四个圆角
    private static final float[] radiusTop = {radius, radius, radius, radius, 0f, 0f, 0f, 0f};
    //底部矩形的四个圆角
    private static final float[] radiusBottom = {0, 0, 0, 0, radius, radius, radius, radius};
    private static final float[] radiusAll = {radius, radius, radius, radius, radius, radius, radius, radius};

    //门票信息文字的高度
    private int ticketInfoTextH;
    //门票信息内间距
    private final int ticketInfoTextPadding = PixelUtil.dp2px(5);
    private StaticLayout ticketTextStaticLayout;
    private TextPaint ticketTextPaint;
    private int ticketTextH;

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

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

    public TicketInfoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        tableLineW = PixelUtil.dp2px(1.0f);

        pLine = new Paint();
        pLine.setAntiAlias(true);
        pLine.setStrokeWidth(tableLineW);

        pText = new Paint();
        pText.setAntiAlias(true);
        pText.setTextAlign(Paint.Align.CENTER);

        pathRoundRect = new Path();

        topRect = new RectF();
        bottomRect = new RectF();
        highLightRect = new RectF();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        w = MeasureSpec.getSize(widthMeasureSpec);
        rowH = (int) (w * 0.134f);

        computeH();
        setMeasuredDimension(w, h);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        vLine1x = 1 / 5f * w;
        vLine2x = 2 / 5f * w;
        vLine3x = 3 / 5f * w;
        vLine4x = 4 / 5f * w;
        hLine1y = rowH;
        hLine2y = rowH * 2;

        textX1 = vLine1x / 2;
        textX2 = vLine1x   (vLine2x - vLine1x) / 2;
        textX3 = vLine2x   (vLine3x - vLine2x) / 2;
        textX4 = vLine3x   (vLine4x - vLine3x) / 2;
        textX5 = vLine4x   (w - vLine4x) / 2;
        textXEnd = w / 2f;

        topRect.right = w;
        topRect.bottom = rowH * 3;

        bottomRect.top = topRect.bottom;
        bottomRect.right = w;
        bottomRect.bottom = topRect.bottom   ticketTextH;

        highLightRect.left = vLine2x;
        highLightRect.top = hLine1y;
        highLightRect.right = vLine3x;
        highLightRect.bottom = topRect.bottom;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        pathRoundRect.reset();
        pLine.setStyle(Paint.Style.FILL);
        pLine.setColor(tableBgColorTop);
        if (hasTicketInfo()) {
            //画顶部矩形
            pathRoundRect.addRoundRect(topRect, radiusTop, Path.Direction.CW);
            canvas.drawPath(pathRoundRect, pLine);

            //画底部矩形
            pathRoundRect.reset();
            pathRoundRect.addRoundRect(bottomRect, radiusBottom, Path.Direction.CW);
            pLine.setColor(tableBgColorBottom);
        } else {//无门票说明则只画上部分表格
            pathRoundRect.addRoundRect(topRect, radiusAll, Path.Direction.CW);
        }
        canvas.drawPath(pathRoundRect, pLine);

        //画高亮部分矩形
        pLine.setColor(tableBgColorHighLight);
        canvas.drawRect(highLightRect, pLine);

        //四根竖线
        pLine.setColor(tableLineColor);
        pLine.setStrokeWidth(tableLineW / 2);
        canvas.drawLine(vLine1x, 0, vLine1x, topRect.bottom, pLine);
        canvas.drawLine(vLine2x, 0, vLine2x, topRect.bottom, pLine);
        canvas.drawLine(vLine3x, hLine1y, vLine3x, topRect.bottom, pLine);
        canvas.drawLine(vLine4x, hLine1y, vLine4x, topRect.bottom, pLine);
        //两根横线
        canvas.drawLine(vLine1x, hLine1y, w, hLine1y, pLine);
        canvas.drawLine(0, hLine2y, w, hLine2y, pLine);

        pText.setColor(textColorBlack);
        pText.setTextSize(blackTextSize);
        pText.setTypeface(getTypeface());
        //计算baseline
        float baseline = hLine2y / 2   getTextDis();

        //市场价 黑色大字
        canvas.drawText(text1, textX1, baseline, pText);
        //第一行黑色大字
        baseline = hLine1y / 2   getTextDis();
        canvas.drawText(text2, textX2, baseline, pText);
        canvas.drawText(text3, vLine2x   (w - vLine2x) / 2, baseline, pText);

        //第二行小字
        baseline = hLine1y   (hLine2y - hLine1y) / 2   getTextDis();
        pText.setTextSize(grayTextSize);
        canvas.drawText(text4, textX2, baseline, pText);
        canvas.drawText(text5, textX4, baseline, pText);
        canvas.drawText(text6, textX5, baseline, pText);
        pText.setColor(Color.WHITE);
        canvas.drawText(text4, textX3, baseline, pText);

        //第三行 画价格、随行人数
        if (ticketInfo != null) {
            pText.setTextSize(redTextSize);
            pText.setColor(textColorBlack);

            baseline = hLine2y   (topRect.bottom - hLine2y) / 2   getTextDis();

            //市场价
            canvas.drawText(limitTextLength(ticketInfo.price), textX1, baseline, pText);
            //出行总人数
            canvas.drawText(limitTextLength(ticketInfo.discounts_num), textX5, baseline, pText);

            //持卡者、同行者价格
            pText.setColor(Color.WHITE);
            canvas.drawText(limitTextLength(ticketInfo.discounts_member), textX3, baseline, pText);
            pText.setColor(textColorRed);
            canvas.drawText(limitTextLength(ticketInfo.single), textX2, baseline, pText);
            canvas.drawText(limitTextLength(ticketInfo.discounts), textX4, baseline, pText);

            //底部门票说明
            if (hasTicketInfo() && ticketTextStaticLayout != null) {
                canvas.save();
                //设定文字开始绘制的坐标,该坐标对应文字的left,top
                canvas.translate(ticketInfoTextPadding, topRect.bottom   ticketInfoTextPadding   (bottomRect.bottom - bottomRect.top - ticketInfoTextH - 2 * ticketInfoTextPadding) / 2);
                ticketTextStaticLayout.draw(canvas);
                canvas.restore();
            }
        }
    }

    private void computeH() {
        if (hasTicketInfo() && w > 2 * ticketInfoTextPadding) {
            if (ticketTextPaint == null) {
                ticketTextPaint = new TextPaint();
                ticketTextPaint.setColor(textColorGray);
                ticketTextPaint.setTextSize(redTextSize);
                ticketTextPaint.setAntiAlias(true);
            }
            //此处每次都创建新对象来获取ticket_info最新值
            ticketTextStaticLayout = new StaticLayout(ticketInfo.ticket_info, ticketTextPaint, w - 2 * ticketInfoTextPadding, Layout.Alignment.ALIGN_CENTER, 1.1F, 1.1F, true);
            ticketInfoTextH = ticketTextStaticLayout.getHeight();

            h = (int) (0.4 * w)   ticketTextH;
        } else {
            h = (int) (0.4 * w);
        }

        ticketTextH = Math.max((ticketInfoTextH   ticketInfoTextPadding * 2), rowH);
        h = hasTicketInfo() ? (int) (0.4 * w)   ticketTextH : (int) (0.4 * w);
    }

    private Typeface getTypeface() {
        Typeface roboto = Typeface.create("sans-serif-medium", Typeface.NORMAL);
        if (roboto == null || roboto.getStyle() == Typeface.NORMAL)
            roboto = Typeface.DEFAULT_BOLD;

        return roboto;
    }

    /**
     * 设置pText的字体大小等属性时,更新文字居中距离
     *
     * @return 文字居中的y坐标
     */
    private float getTextDis() {
        Paint.FontMetrics fontMetrics = pText.getFontMetrics();
        return (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
    }

    /**
    * ticketInfo为后台返回的数据模型,此处不再贴出
    */
    public void setTicketInfo(ScenicDetailInfo.TicketInfo ticketInfo) {
        this.ticketInfo = ticketInfo;
        if (ticketInfo != null) {
            computeH();
            //重新layout,确定view的绘制区域
            requestLayout();
        } else {
            invalidate();
        }
    }

    private String limitTextLength(String src) {
        if (!TextUtils.isEmpty(src) && src.length() > 5)
            src = src.substring(0, 5)   "...";
        return src;
    }

    private boolean hasTicketInfo() {
        return ticketInfo != null && !TextUtils.isEmpty(ticketInfo.ticket_info);
    }
}

可以看到无非就是定义一些颜色啊、坐标啊这些,在onLayout的时候计算出对应的值,然后draw即可,主要是思路要清晰,我这里是从上而下,从左到右的思路绘制。

这个view也有个弊端,就是大小及样式固定,里面的文字均为单行展示没处理自动换行,不过满足需求就好了啊,不要那么折腾,不然头发又要变少了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持Devmax。

Android自定义view绘制表格的方法的更多相关文章

  1. html5 canvas合成海报所遇问题及解决方案总结

    这篇文章主要介绍了html5 canvas合成海报所遇问题及解决方案总结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Html5 video标签视频的最佳实践

    这篇文章主要介绍了Html5 video标签视频的最佳实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  3. HTML5在微信内置浏览器下右上角菜单的调整字体导致页面显示错乱的问题

    HTML5在微信内置浏览器下,在右上角菜单的调整字体导致页面显示错乱的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  4. ios – containerURLForSecurityApplicationGroupIdentifier:在iPhone和Watch模拟器上给出不同的结果

    我使用默认的XCode模板创建了一个WatchKit应用程序.我向iOSTarget,WatchkitAppTarget和WatchkitAppExtensionTarget添加了应用程序组权利.(这是应用程序组名称:group.com.lombax.fiveminutes)然后,我尝试使用iOSApp和WatchKitExtension访问共享文件夹URL:延期:iOS应用:但是,测试NSURL

  5. ios – 如何在父视图上添加子视图控制器的视图

    再现.从而:

  6. Ionic – Splash Screen适用于iOS,但不适用于Android

    我有一个离子应用程序,其中使用CLI命令离子资源生成的启动画面和图标iOS版本与正在渲染的启动画面完美配合,但在Android版本中,只有在加载应用程序时才会显示白屏.我检查了config.xml文件,所有路径看起来都是正确的,生成的图像出现在相应的文件夹中.(我使用了splash.psd模板来生成它们.我错过了什么?这是config.xml文件供参考,我觉得我在这里做错了–解决方法在config.xml中添加以下键:它对我有用!

  7. ios – 实例化ViewController w / xib时的帧大小不正确

    我有一个视图控制器,看起来像:当我通过让spotViewController=SpotViewController实例化视图控制器并将其推送到导航控制器时,结果框架在viewDidLoad和viewWillAppear中都是不正确的.它给了我这是界面构建器中的大小.为什么会发生这种情况以及使用xib实例化视图控制器以确保帧正确的正确方法是什么?解决方法这将解决您的问题,UIViewController从xib加载,在viewDidLoad期间保持xib大小:

  8. ios – 无法启动iPhone模拟器

    /Library/Developer/CoreSimulator/Devices/530A44CB-5978-4926-9E91-E9DBD5BFB105/data/Containers/Bundle/Application/07612A5C-659D-4C04-ACD3-D211D2830E17/ProductName.app/ProductName然后,如果您在Xcode构建设置中选择标准体系结构并再次构建和运行,则会产生以下结果:dyld:lazysymbolbindingFailed:Symbol

  9. Xamarin iOS图像在Grid内部重叠

    heyo,所以在Xamarin我有一个使用并在其中包含一对,所有这些都包含在内.这在Xamarin.Android中看起来完全没问题,但是在Xamarin.iOS中,图像与标签重叠.我不确定它的区别是什么–为什么它在Xamarin.Android中看起来不错但在iOS中它的全部都不稳定?

  10. ios – CAGradientLayer不工作

    参见英文答案>DrawinggradientonUIViewnotworkingwithiOS91个我创建了一个新项目.我链接了QuartzCore.framework并导入了在ViewController.m中.这是代码.我尝试将视图的背景颜色设置为clearColor,在viewDidAppear中调用它,但它们都没有工作.我真的不知道自己错过

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部