Android UI控件組合應用之二:按鈕布局
在上一篇文章中,我們已經完成了數據模型的代碼,并且為了測試方便,在類中直接為很多成員變量提供了默認值。接下來,進入到界面部分。
縱觀整個界面,可以分成上下兩塊,一塊是頂端的操作條,另一塊是占主體的列表框。
先從頂端的操作條開始,在這里,很容易分解成三個部分,左側的寫微博按鈕,中間的用戶名顯示,右側的刷新按鈕。兩個按鈕的風格是一樣的,都是有常規和按下兩種狀態,這種按鈕是非常常用的,我的做法是:
1. 在drawable文件夾下建立兩個xml文件,分別對應了兩個按鈕;
2. 每個xml文件中使用selector標簽定義常規狀態和選中狀態的兩個圖片資源;
3. 在Activity的布局中使用ImageButton,指定按鈕的background為透明,并指定src為剛才定義的兩個xml。
下面是這兩個xml文件的內容:
- view plaincopy to clipboardprint?
- <?xml version="1.0" encoding="utf-8"?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_pressed="true" android:drawable="@drawable/title_new_selected" />
- <item android:drawable="@drawable/title_new_normal" />
- </selector>
- view plaincopy to clipboardprint?
- <?xml version="1.0" encoding="utf-8"?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_pressed="true" android:drawable="@drawable/title_reload_selected" />
- <item android:drawable="@drawable/title_reload_normal" />
- </selector>
在main.xml文件中,進行這一部分的布局,對于這三個界面元素而言,有明確的位置關系,因此采用RelativeLayout合適,內容如下:
- view plaincopy to clipboardprint?
- <RelativeLayout
- android:layout_width="fill_parent" android:layout_height="44dp"
- android:background="@drawable/titlebar_lightgray_bg" android:orientation="horizontal">
- <ImageButton android:id="@+id/BtnWrite"
- android:layout_width="wrap_content" android:layout_height="fill_parent"
- android:layout_alignParentLeft="true" android:background="@android:color/transparent"
- android:src="@drawable/write_button">
- </ImageButton>
- <TextView android:id="@+id/TextViewUsername"
- android:layout_width="fill_parent" android:layout_height="fill_parent"
- android:textColor="@color/black" android:gravity="center" android:textSize="18sp">
- </TextView>
- <ImageButton android:id="@+id/BtnRefresh"
- android:layout_width="wrap_content" android:layout_height="fill_parent"
- android:layout_alignParentRight="true" android:background="@android:color/transparent"
- android:src="@drawable/refresh_button">
- </ImageButton>
- </RelativeLayout>
最后,指定RelativeLayout的background為背景圖片即可。
本次用到的圖片有: