Android自定義TextView實(shí)現(xiàn)drawableLeft內(nèi)容居中
更新時(shí)間:2017年06月19日 14:48:46 投稿:lqh
這篇文章主要介紹了Android自定義TextView實(shí)現(xiàn)drawableLeft內(nèi)容居中的相關(guān)資料,需要的朋友可以參考下
如何實(shí)現(xiàn)使用TextView的DrawableLeft使圖片和文字居中顯示呢???
代碼如下:
1.首先自定義一個(gè)類,繼承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)用日期類Calendar實(shí)現(xiàn)時(shí)間運(yùn)算的相關(guān)技巧,需要的朋友可以參考下2016-03-03
ubuntu用wifi連接android調(diào)試程序的步驟
這篇文章主要介紹了ubuntu用wifi連接android調(diào)試程序的步驟,需要的朋友可以參考下2014-02-02
簡單實(shí)現(xiàn)Android驗(yàn)證碼
在登錄或者注冊(cè)的時(shí)候要求輸入驗(yàn)證碼,這篇文章主要為大家詳細(xì)介紹了如何簡單實(shí)現(xiàn)Android驗(yàn)證碼的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12
Compose?動(dòng)畫藝術(shù)之屬性動(dòng)畫探索
這篇文章主要介紹了Compose動(dòng)畫藝術(shù)之屬性動(dòng)畫探索,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
Android開發(fā)手冊(cè)shape屬性和子屬性使用說明
這篇文章主要為大家介紹了Android開發(fā)手冊(cè)shape屬性和子屬性使用說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06

