android自定义换行居中CenterTextView

在我们开发app时,TextView一定是使用最多的控件了,android自带的TextView的功能也十分强大,但还是有些小的地方不能满足我们的需求,几天要说的这个功能也是开发中很常见的,就是,在我们显示一段超过屏幕宽度的 String时,TextView会自动换行,但系统默认的换行效果是顶起,而不是美工要求的居中。这时候,就需要我们对系统的TextView做一些改造,已使得换行后文字能够居中显示。

先看下效果图:

这种布局在IOS上很容易就实现了,android还的自定义一个View.

思路:在看android.text包中的源码时,发现几个从来没用到的类,包括:Layout,StaticLayout,DeynamicLayout等几个类,百度后得知这几个类的大概作用:

这三个Layout,就是用来对android的CharSequence及其子类进行布局的,为其传入不同的Alignment,就按照不同的Alignment去处理。代码很简单,只要从写TextView即可,代码如下:package com.example.materialdesigndemo;import android.content.Context;import android.graphics.Canvas;import android.graphics.Paint;import android.text.Layout.Alignment;import android.text.StaticLayout;import android.text.TextPaint;import android.util.AttributeSet;import android.widget.TextView;/********************************************************** * @文件名称:CenterTextView.java * @文件作者:rzq * @创建时间:2015年7月2日 上午10:12:16 * @文件描述:换行居中显示TextView * @修改历史:2015年7月2日创建初始版本 **********************************************************/public class CenterTextView extends TextView{private StaticLayout myStaticLayout;private TextPaint tp;public CenterTextView(Context context, AttributeSet attrs){super(context, attrs);}@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh){super.onSizeChanged(w, h, oldw, oldh);initView();}private void initView(){tp = new TextPaint(Paint.ANTI_ALIAS_FLAG);tp.setTextSize(getTextSize());tp.setColor(getCurrentTextColor());myStaticLayout = new StaticLayout(getText(), tp, getWidth(), Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);}@Overrideprotected void onDraw(Canvas canvas){myStaticLayout.draw(canvas);}} 使用: <RelativeLayout xmlns:android=""xmlns:tools=""android:layout_width="match_parent"android:layout_height="match_parent" ><TextViewandroid:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_marginTop="30dp"android:text="最美的不是下雨天,是和你一起躲过雨的屋檐,美丽的画面。" /><com.example.materialdesigndemo.CenterTextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/text"android:layout_centerHorizontal="true"android:layout_marginTop="30dp"android:text="最美的不是下雨天,是和你一起躲过雨的屋檐,美丽的画面。" /></RelativeLayout>

代码很简单,基本只需要重写onDraw()方法,让StaticLayout的实例去重新处理一下即可。这样处理后弊端就是,我们的CenterTextView只能显示文字,无法再显示drawableLeft等,如果需要,,就需要在onDraw()方法中进行更复杂的处理。

Demo

版权声明:本文为博主原创文章,未经博主允许不得转载。

可是旅行的彼时那刻我的心情一直是好的吗?

android自定义换行居中CenterTextView

相关文章:

你感兴趣的文章:

标签云: