關於Android中界麵XML文件的繪製順序
在開發Android程序的時候經常會遇到寫界麵XML文件的問題,其中感觸最深的就是一些控件顯示不出來或者顯示的位置不對。通過不斷地調試終於發現了一些原因,現在寫出來,希望可以幫到大家。
之前我寫過一個很簡單的界麵:
<?xmlversion="1.0"encoding="utf-8" ?> <LinearLayoutxmlns:andro android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <RelativeLayoutxmlns:andro android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListViewandroid: android:layout_height="wrap_content" android:layout_width="fill_parent" android:paddingTop="15dp" android:paddingBottom="15dp" android:layout_alignParentTop="true" /> <Buttonandroid: android:layout_width="fill_parent" android:layout_height="60dp" android:text="設置" android:gravity="center" android:textSize="15sp" android:layout_alignParentBottom="true" android:layout_below="@id/listview_mibTree"/> </RelativeLayout> </LinearLayout>
但是這樣的界麵如果ListView的內容太長的話,底部的按鈕就消失了。這是因為,係統在解析這個.XML文件的時候應該是順序解析順序繪製的一個過程,根據這個XML文件的邏輯,會先繪製ListView,之後在繪製底部的按鈕,言下之意就是先繪製ListView,如果ListView的內容過多,那麼勢必為需要向下滑動瀏覽,ListView自己的內容都展示不完,哪裏又還有位置留給底部的按鈕呢?
所以正確的邏輯應該是:
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:andro android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <RelativeLayoutxmlns:andro android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android: android:layout_width="fill_parent" android:layout_height="60dp" android:text="設置" android:gravity="center" android:textSize="15sp" android:layout_alignParentBottom="true"/> <ListView android: android:layout_height="wrap_content" android:layout_width="fill_parent" android:paddingTop="15dp" android:paddingBottom="15dp" android:layout_alignParentTop="true" android:layout_above="@id/btn_setInMain" ></ListView> </RelativeLayout> </LinearLayout>
這時先解析的是按鈕控件,所以已經現將其繪製到了界麵的底部,這時就算ListView的內容再多,也不會影響Button的顯示。而且其中ListView有一行代碼:
android:layout_above="@id/btn_setInMain"
所以在編寫界麵的時候,隻要搞清楚了其繪製的順序,有很多問題就可以解決了。
表明ListView是繪製在Button之上的,所以該ListView不會把Button覆蓋掉。
最後的界麵:
所以隻要弄清楚了其繪製的順序,有的問題就容易解決了。
最後更新:2017-04-03 18:51:52