Android代碼設置TextView的頂部圖及設置圖與字體之間距離

終於建了一個自己個人小站:https://huangtianyu.gitee.io,以後優先更新小站博客,歡迎進站,O(∩_∩)O~~

現在很多的設計底部都是幾個Tab標籤,每個標籤都是上邊是圖片,下邊是文字。下面提供一種簡單的方式來實現這個:

<TextView 
	android:id="@+id/tv_versionstatus"
        android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:drawablePadding="5dp"
	android:drawableTop="@drawable/icon_home"
	android:text="首頁"
	android:textColor="#363636"
	android:textSize="20sp" /> 

然後在代碼中設置圖片和圖片與文字間的間距。代碼設置如下:

    //設置TextView的頂部圖標,其中setCompoundDrawablesWithIntrinsicBounds對應的是left,top,right,bottom圖標
    private void setHomeMenuTextDrawableTop(TextView textView, Drawable drawable) {
        if (textView == null || drawable == null) {
            return;
        }
        textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        textView.invalidate();
    }

通過代碼設置圖片和文字之間的間距:

textView.setCompoundDrawablePadding(padding) ;//int padding 代碼設置文字和圖片間距 

這裏說個問題,就是有時候設置了圖片和文字間距在實際使用時並沒有看到效果,這是因爲view的寬度過寬,導致view內文本和圖片間距過大,那我們可以通過設置paddingLeft、paddingRight、paddingTop、paddingBottom來縮小這個間距.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:text="@string/xian_txt"
    android:drawableRight="@mipmap/ic_triangle_down"
    android:background="@android:color/transparent"
    android:drawablePadding="6dp"
    android:gravity="center"
    android:paddingRight="24dp"
    android:paddingLeft="24dp"
    />


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章