android自己定义换行居中CenterTextView

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

这时候,就须要我们对系统的TextView做一些改造。已使得换行后文字可以居中显示。

    先看下效果图:

    

    这样的布局在IOS上非常easy就实现了,android还的自己定义一个View.

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

                这三个Layout,就是用来对android的CharSequence及其子类进行布局的,为其传入不同的Alignment,就依照不同的Alignment去处理。代码非常easy,仅仅要从写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);
	}

	@Override
	protected 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);
	}

	@Override
	protected void onDraw(Canvas canvas)
	{
		myStaticLayout.draw(canvas);
	}
}
     使用:     
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android: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.CenterTextView android: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>

      代码非常easy,基本仅仅须要重写onDraw()方法。让StaticLayout的实例去又一次处理一下就可以。这样处理后弊端就是。我们的CenterTextView仅仅能显示文字。无法再显示drawableLeft等,假设须要,就须要在onDraw()方法中进行更复杂的处理。

  Demo

原文地址:https://www.cnblogs.com/cynchanpin/p/6703857.html