標籤:系統 檔案的 .com getc context 繪製 UI android 註冊
Android:日常學習筆記(7)———探究UI開發(4)UI概述
View 和 ViewGrou
Android 應用中的所有使用者介面元素都是使用 View 和 ViewGroup 對象構建而成。View 對象用於在螢幕上繪製可供使用者互動的內容。ViewGroup 對象用於儲存其他 View(和 ViewGroup)對象,以便定義介面的布局。
說明:
View是安卓中最基本的一種UI,它可以在螢幕上繪製一塊矩形地區,並能響應這塊地區的各種事件,我們使用的各種控制項都是在View的基礎上進行的添加和完善。ViewGroup則是一種特殊的View,他可以包含很多View和子ViewGroup,是一個用於放置控制項和布局的容器。
引入布局
比如現在我們要替換系統預設的標題列,改為如下所示:
即兩邊是兩個按鈕,中間是標題文字,XML設定檔如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary"> <ImageButton android:layout_width="wrap_content" android:layout_height="match_parent" android:src="@drawable/previous_24px" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:gravity="center" android:text="我是標題文字" android:textColor="#fff" android:textSize="24sp" /> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/next_24px" /></LinearLayout>
我們面臨一個問題,我們要讓所有的活動頁面都採用這個標題列該怎麼做呢?
我們可以單獨將這個標題列寫到一個XML檔案中,然後在其他任意使用此標題列的活動的布局檔案中引入此XML即可。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <include layout="@layout/panel_title"/></LinearLayout>
建立自訂控制項
說明:
引入布局的技巧的確實解決了重複編寫布局代碼的問題,但是如果布局中的一些控制項要求能夠響應事件,我們還是需要在每個活動中為這些控制項單獨編寫一次事件註冊的代碼,比如標題列中的返回按鈕,都是銷毀當前活動。為了避免重複代碼,我們可以使用自訂控制項的方式來解決。
代碼:
1.建立TitleLayout(繼承自LinearLayout)
public class TitleLayout extends LinearLayout { public TitleLayout(Context context, @Nullable AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.panel_title,this); }}
說明:
首先我們重寫了LinerLayout的建構函式,在布局中引入TitleLayout控制項就會調用這個建構函式。然後在建構函式中對標題列布局進行動態載入,這就需要用到LayoutInflater了。通過LayoutInflater的form()方法可以構建出一個LayoutInflater對象,然後調用Inflate()就可以動態載入一個布局檔案。
inflate接受兩個參數:
- 第一個是布局檔案的ID
- 第二個參數是給載入好的布局再添加一個父布局,此處為this
2.為按鈕綁定事件
public class TitleLayout extends LinearLayout { public TitleLayout(Context context, @Nullable AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.panel_title,this); ImageButton titleBack = (ImageButton) findViewById(R.id.title_back); titleBack.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast.makeText(getContext(),"活動銷毀",Toast.LENGTH_LONG).show(); } }); }}
3.在布局檔案中添加這個自訂控制項
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.zy.dealhelper.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content"/></LinearLayout>
說明:
添加自訂控制項和添加普通控制項的方式基本一樣,只不過在添加自訂控制項的時候需要指明控制項的具體類名。
Android:日常學習筆記(7)———探究UI開發(4)