Android-自定义控件
简介
有时,当系统自带的控件不能满足我们的需求时,我们可以利用控件都继承自View的特性来自定义一个控件,下面以自定义的一个标题栏为例,演示安卓中的自定义控件
步骤
一、 新建一个布局title.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| <?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:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/bt_back" android:layout_width="30dp" android:layout_height="30dp" android:layout_gravity="center" android:layout_margin="5dp" android:background="@drawable/back" android:textColor="#fff"/>
<TextView android:id="@+id/tv_title" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="Title Text" android:textColor="#000" android:textSize="20sp" /> <Button android:id="@+id/bt_edit" android:layout_width="30dp" android:layout_height="30dp" android:layout_gravity="center" android:background="@drawable/edit" />
</LinearLayout> <View android:layout_marginBottom="3dp" android:layout_width="match_parent" android:layout_height="1.5dp" android:background="#000"/> </LinearLayout>
|
二、在activity_main.xml中使用
1 2 3 4 5 6 7 8 9 10 11
| <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity">
<include layout="@layout/title"/>
</LinearLayout>
|
三、在MainActivity中删除系统自带的标题栏
1 2 3 4 5 6 7 8 9 10
| public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar(); if(actionBar!=null)actionBar.hide(); } }
|
四、在Java文件中实现标题栏上两个按钮的点击事件(略)
五、自定义控件的其余用法请自行学习。