標籤:
一、關於View與布局,首先
可以看到:
- View是Android中最基本的UI組件,它可以在螢幕上繪製一塊矩形地區,並能響應這個地區的各種事件;
- ViewGroup是一種特殊的View,它可以包含很多子View和子ViewGroup,是一種用於放置控制項和布局的容器;
- 我們所使用的所有控制項都是直接或間接繼承View的,各種控制項其實就是在View的基礎上添加了各自的功能;
- 所有布局都是直接繼承自ViewGroup的;
二、定義自訂控制項需要:
以自訂一個標題列為例,效果如(請無視它的難看程度)
自訂布局檔案:
<?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="#444" android:orientation="horizontal" > <Button android:id="@+id/btnBack" android:layout_width="33dip" android:layout_height="33dip" android:background="@drawable/icon_back" /> <TextView android:id="@+id/tvTitle" android:layout_width="0dip" android:layout_height="33dip" android:layout_weight="1" android:background="#444" android:gravity="center" android:text="標題列" android:textColor="#fff" /> <Button android:id="@+id/btnEdit" android:layout_width="33dip" android:layout_height="33dip" android:background="@drawable/icon_edit" /></LinearLayout>
自訂控制項的類:
package com.matclone.CustomUIViewTest;import android.app.Activity;import android.content.Context;import android.util.AttributeSet;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;public class TitleBar extends LinearLayout { private Button btnBack = null; private TextView tvTitle = null; private Button btnEdit = null; public TitleBar(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub LayoutInflater.from(context).inflate(R.layout.title_bar, this); btnBack = (Button) this.findViewById(R.id.btnBack); tvTitle = (TextView) this.findViewById(R.id.tvTitle); btnEdit = (Button) this.findViewById(R.id.btnEdit); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub ((Activity)getContext()).finish(); } }); btnEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(getContext(), "你點擊了EDIT按鈕", Toast.LENGTH_SHORT).show(); } }); } public void setTitle(String title) { this.tvTitle.setText(title); }}
三、使用自訂控制項需要:
在其他的活動的布局檔案中引入自訂控制項:
<?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" android:orientation="vertical" > <com.matclone.CustomUIViewTest.TitleBar android:id="@+id/titleBar" android:layout_width="match_parent" android:layout_height="wrap_content" > </com.matclone.CustomUIViewTest.TitleBar></LinearLayout>
《Android第一行代碼》學習記錄008 - 建立自訂控制項