Android自定義TextView實現(xiàn)drawableLeft內(nèi)容居中
更新時間:2017年06月19日 14:48:46 投稿:lqh
這篇文章主要介紹了Android自定義TextView實現(xiàn)drawableLeft內(nèi)容居中的相關(guān)資料,需要的朋友可以參考下
如何實現(xiàn)使用TextView的DrawableLeft使圖片和文字居中顯示呢???
代碼如下:
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"http://給圖片和文字之間設(shè)置填充
android:text="都完成"
android:textColor="#333333"
android:textSize="12sp" />
3。ok實現(xiàn)效果 如下。。。

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Android 實現(xiàn)沉浸式狀態(tài)欄的方法
沉浸式狀態(tài)欄的來源就是很多手機用的是實體按鍵,沒有虛擬鍵,于是開了沉浸模式就只有狀態(tài)欄消失了。下面腳本之家小編給大家介紹Android 實現(xiàn)沉浸式狀態(tài)欄,需要的朋友可以參考下2015-09-09
Android點擊Button實現(xiàn)切換點擊圖片效果的示例
今天小編就為大家分享一篇關(guān)于Android點擊Button實現(xiàn)切換點擊圖片效果的示例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
Retrofit 創(chuàng)建網(wǎng)絡(luò)請求接口實例過程
這篇文章主要為大家介紹了Retrofit 創(chuàng)建網(wǎng)絡(luò)請求接口實例過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12

