Android自定義TextView實(shí)現(xiàn)drawableLeft內(nèi)容居中
如何實(shí)現(xiàn)使用TextView的DrawableLeft使圖片和文字居中顯示呢???
代碼如下:
1.首先自定義一個(gè)類(lèi),繼承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,實(shí)現(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"http://給圖片和文字之間設(shè)置填充 android:text="都完成" android:textColor="#333333" android:textSize="12sp" />
3。ok實(shí)現(xiàn)效果 如下。。。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Android編程實(shí)現(xiàn)根據(jù)不同日期計(jì)算天數(shù)差的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)根據(jù)不同日期計(jì)算天數(shù)差的方法,涉及Android調(diào)用日期類(lèi)Calendar實(shí)現(xiàn)時(shí)間運(yùn)算的相關(guān)技巧,需要的朋友可以參考下2016-03-03ubuntu用wifi連接android調(diào)試程序的步驟
這篇文章主要介紹了ubuntu用wifi連接android調(diào)試程序的步驟,需要的朋友可以參考下2014-02-02簡(jiǎn)單實(shí)現(xiàn)Android驗(yàn)證碼
在登錄或者注冊(cè)的時(shí)候要求輸入驗(yàn)證碼,這篇文章主要為大家詳細(xì)介紹了如何簡(jiǎn)單實(shí)現(xiàn)Android驗(yàn)證碼的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12Compose?動(dòng)畫(huà)藝術(shù)之屬性動(dòng)畫(huà)探索
這篇文章主要介紹了Compose動(dòng)畫(huà)藝術(shù)之屬性動(dòng)畫(huà)探索,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09Android開(kāi)發(fā)手冊(cè)shape屬性和子屬性使用說(shuō)明
這篇文章主要為大家介紹了Android開(kāi)發(fā)手冊(cè)shape屬性和子屬性使用說(shuō)明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06