成都创新互联网站制作重庆分公司

如何在Android中利用TextView实现一个内容居中效果

本篇文章给大家分享的是有关如何在Android中利用TextView实现一个内容居中效果,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

成都创新互联公司是一家专业提供拱墅企业网站建设,专注与成都网站制作、做网站、H5高端网站建设、小程序制作等业务。10年已为拱墅众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。

1.首先自定义一个类,继承TextView

package com.test.signcalendar.weight;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 自定义TextView,实现drawableLeft可以和文字一起居中
 * @author HLQ
 * @createtime 2016年3月20日04:14:36
 *
 */
public class DrawableCenterTextView extends TextView {

  public DrawableCenterTextView(Context context, AttributeSet attrs,
      int defStyle) {
    super(context, attrs, defStyle);
  }

  public DrawableCenterTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public DrawableCenterTextView(Context context) {
    super(context);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    Drawable[] drawables = getCompoundDrawables();
    if (drawables != null) {
      Drawable drawableLeft = drawables[0];
      if (drawableLeft != null) {
        float textWidth = getPaint().measureText(getText().toString());
        int drawablePadding = getCompoundDrawablePadding();
        int drawableWidth = 0;
        drawableWidth = drawableLeft.getIntrinsicWidth();
        float bodyWidth = textWidth + drawableWidth + drawablePadding;
        canvas.translate((getWidth() - bodyWidth) / 2, 0);
      }
    }
    super.onDraw(canvas);
  }
}

2.之后在xml布局文件中直接引用即可。。。

3。ok实现效果 如下。。。

如何在Android中利用TextView实现一个内容居中效果

以上就是如何在Android中利用TextView实现一个内容居中效果,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。


名称栏目:如何在Android中利用TextView实现一个内容居中效果
分享网址:http://cxhlcq.com/article/ihhhhd.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部