您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關如何在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)容居中效果,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。