最近在用原生的控件和佈局繪製一些界面並使用,雖然這些都是Android基本知識,但是有的時候真的感覺力不從心,感覺有必要對Android常用的控件和佈局做一個系統的瞭解。後續一個月甚至更多的時間都會圍繞這個主題展開,畢竟這裏面還是有不少高級控件的,我也會盡量結合應用深入的進行了解。
今天是六一兒童節,我們來學習一個相對簡單一點的控件Space,下面就先來看看它的官方文檔介紹:
/** * Space is a lightweight View subclass that may be used to create gaps between components * in general purpose layouts. */
Space是一個輕量級的View子類,通常將其用於創建組件之間間隙的目的
可見這個控件主要用於協助佈局使用,有點類似ConstraintLayout中的guideLine的作用,這個後面我們會說到,下面我們就來看看Space的具體顯示樣式:
<Space
android:id="@+id/space_test"
android:layout_width="20dp"
android:layout_height="match_parent" />
運行之後,界面上什麼都沒有,但是在設計Design中,我們的控件是添加了的:
下面看一下它的構造方法一探究竟,Space一共有四個構造方法,但是都會調用下面的這個:
/**
* {@inheritDoc}
*/
public Space(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
if (getVisibility() == VISIBLE) {
setVisibility(INVISIBLE);
}
}
我想,看到這裏就不用多說了,Space在創建的時候默認是Invisible的,所以你設置什麼也沒有用,你設置了以下屬性,它也會強行把你變爲不可見。
android:visibility="visible"
那我們爲其添加一個背景,並且在邏輯代碼中把其轉爲可見的狀態:
<Space
android:id="@+id/space_test"
android:background="@color/colorPrimary"
android:layout_width="20dp"
android:layout_height="match_parent" />
testSpace=findViewById(R.id.space_test);
testSpace.setVisibility(View.VISIBLE);
運行之後還是什麼都沒有,這個時候真的要抓狂了,我們還是只能在源碼中找到答案,因爲背景以及顯示的樣式肯定是通過draw()方法繪製在出來的,所以我們重點看一下Space的draw()方法實現:
/**
* Draw nothing.
*
* @param canvas an unused parameter.
*/
@Override
public void draw(Canvas canvas) {
}
WTF,它居然什麼都沒有幹,這樣也就不難解釋爲什麼你設置什麼它都不會顯示出來的情況了,好了,我們再回到最開始的關於Space的文檔介紹:
/*Space is a lightweight View subclass that may be used to create gaps between components in general purpose layouts. */
Space是一個輕量級的View子類,通常將其用於創建組件之間間隙的目的
這個時候再回過來看一下,好像描述的很有道理,是一個直接繼承View的輕量級的用於創建組件之間空隙的佈局的控件 ,所以只需要重寫onMeasure()獲取尺寸即可,不要只想draw這些耗時的渲染工作。這也是這個控件的主要用途之一。單單從上面的介紹來看,這個Space完全可以用控件的以下屬性來替代:
android:layout_marginLeft="x"
android:layout_marginTop="y"
android:layout_marginRight="m"
android:layout_marginBottom="n"
下面就來舉一個在佈局適配中經常使用的且這幾個屬性很難解決的佈局問題:我們想在屏幕垂直方向2/5到3.5/5顯示一個TextView。下面就兩種方式簡單理一下思路:
- 使用佈局屬性:先計算屏幕的高度,計算TextView的高度,計算TextView到頂部的高度
- 使用Space:TextView上下放一個Space,上面Space佔比2/5,下面佔比1.5/5即可
下面只給出方式2的實現,方式不推薦也不使用:
<Space
android:id="@+id/space_test_top"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2" />
<TextView
android:id="@+id/title_book"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.5"
android:gravity="center"
android:text="我是用於Space的測試文本"
android:textAllCaps="false"
android:textSize="25sp"
android:textStyle="bold" />
<Space
android:id="@+id/space_test_bottom"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.5" />
可見,使用任何佈局我們都可以完成適配,並且使用Space沒有渲染操作,效率很高。好了,到這裏,關於Space就介紹完了。祝大家六一兒童節快樂。
注:歡迎掃碼關注