Android自定義TextView實(shí)現(xiàn)drawableLeft內(nèi)容居中
如何實(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使用GRPC進(jìn)行通信過(guò)程解析
這篇文章主要給大家介紹了在Android上使用grpc的方法教程,文中通過(guò)示例代碼給大家詳細(xì)介紹了在android上使用grpc的方法以及可能遇到的種種問題的解決方法,對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧2023-02-02
Android 實(shí)現(xiàn)沉浸式狀態(tài)欄的方法
沉浸式狀態(tài)欄的來(lái)源就是很多手機(jī)用的是實(shí)體按鍵,沒有虛擬鍵,于是開了沉浸模式就只有狀態(tài)欄消失了。下面腳本之家小編給大家介紹Android 實(shí)現(xiàn)沉浸式狀態(tài)欄,需要的朋友可以參考下2015-09-09
自己實(shí)現(xiàn)Android View布局流程
這篇文章主要介紹了自己實(shí)現(xiàn)Android View布局流程,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03
Android點(diǎn)擊Button實(shí)現(xiàn)切換點(diǎn)擊圖片效果的示例
今天小編就為大家分享一篇關(guān)于Android點(diǎn)擊Button實(shí)現(xiàn)切換點(diǎn)擊圖片效果的示例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03
Retrofit 創(chuàng)建網(wǎng)絡(luò)請(qǐng)求接口實(shí)例過(guò)程
這篇文章主要為大家介紹了Retrofit 創(chuàng)建網(wǎng)絡(luò)請(qǐng)求接口實(shí)例過(guò)程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12

