溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Android中利用TextView實現(xiàn)一個內(nèi)容居中效果

發(fā)布時間:2020-12-08 15:43:24 來源:億速云 閱讀:210 作者:Leah 欄目:移動開發(fā)

本篇文章給大家分享的是有關如何在Android中利用TextView實現(xiàn)一個內(nèi)容居中效果,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

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,實現(xiàn)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布局文件中直接引用即可。。。

<com.test.signcalendar.weight.DrawableCenterTextView
          android:id="@+id/textView1111"
          android:layout_width="0dp"
          android:layout_height="wrap_content"
          android:layout_weight="1"
          android:drawableLeft="@drawable/fmhp_mine_health_plan_signcalendar_finish_status_bg"
          android:drawablePadding="5dp"//給圖片和文字之間設置填充
          android:text="都完成"
          android:textColor="#333333"
          android:textSize="12sp" />

3。ok實現(xiàn)效果 如下。。。

如何在Android中利用TextView實現(xiàn)一個內(nèi)容居中效果

以上就是如何在Android中利用TextView實現(xiàn)一個內(nèi)容居中效果,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI