
:更多精品文章分類
本系列持續更新中….3.3 系統控件不夠用?建立自定義控件
上一節我們學習了 Android 中的一些常用的控件和布局的用法。這裡我們來看一下他們的關系圖
可以看到說有的控件都是直接或者間接繼承
View
,所有的布局都是直接或者間接繼承
ViewGroup
。
View 是 Android 中最基本的一種 UI 元件,它可以在螢幕上繪制一塊矩形區域,并且能夠響應這塊區域的各種事件,是以,我們使用的各種控件其實就是在 View 的基礎的又添加了一些特有的功能。而 ViewGroup 是一種特殊的 View ,它可以包含很多子 View 和 子 ViewGroup,是一個用于放置控件和布局的容器。
那麼當系統給我提供的控件不能滿足我們的需要的時候,我們也可以自己建立符合我們自己需求的控件。
3.4.1 引入布局
我們知道現在的應用程式幾乎在界面頂部都有一個标題欄,雖然 Android 系統已經給我們提供了,但是這裡我們不用它,我們自己建立一個。
我們自己建立一個布局
<?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"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/title_back"
android:background="@color/colorAccent"
android:layout_gravity="center"
android:text="back"
android:textAllCaps="false"
android:textColor="#FFFFFF"/>
<TextView
android:layout_gravity="center"
android:layout_width="0dp"
android:layout_weight="1"
android:textSize="24sp"
android:layout_height="wrap_content"
android:text="Text Title"
android:id="@+id/title_text"
android:gravity="center"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="@color/colorPrimaryDark"
android:text="Edit"
android:textAllCaps="false"/>
</LinearLayout>
就這樣這個簡單的标題欄布局就寫好了,那麼如何使用呢?很簡單,在需要使用的布局中。
<include layout="@layout/title"/>
就添加上面一句話就把剛剛的布局引入了。
使用的時候不要忘了隐藏自帶的标題欄
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
ActionBar actionBar = getSupportActionBar();
if (actionBar !=null){
actionBar.hide();
}
initView();
}
3.4.2 建立自定義控件
引入布局的技巧确實解決了重複編寫布局代碼的問題,但是布局中有一些控件還需要響應事件,這種情況就需要我們來自定義控件了。
建立 TitleLayout 繼承自 LinearLayout,讓它作為我們自定義标題欄的控件。
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button btBack = findViewById(R.id.title_back);
Button btEdit = findViewById(R.id.bt_edit);
btBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
btEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 你自己想做的事情
}
});
}
}
好了這樣一個标題欄自定義控件就完成了。