組合控件的用法:
第一步:新建一個佈局文件,在佈局文件中放置好相應的控件,代碼如下所示。
代碼出處:http://blog.csdn.net/guolin_blog/article/details/17357967
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="50dp"
- android:background="#ffcb05" >
- <Button
- android:id="@+id/button_left"
- android:layout_width="60dp"
- android:layout_height="40dp"
- android:layout_centerVertical="true"
- android:layout_marginLeft="5dp"
- android:background="@drawable/back_button"
- android:text="Back"
- android:textColor="#fff" />
- <TextView
- android:id="@+id/title_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:text="This is Title"
第二步:創建一個類繼承自FrameLayout,在類的構造函數中用了LayoutInflater的inflate()方法來加載剛剛定義的xml佈局文件。關於LayoutInfalter的原理分析可以參考:Android LayoutInflater原理分析,帶你一步步深入瞭解View(一)
參考代碼:
代碼出處:http://blog.csdn.net/guolin_blog/article/details/17357967
- public class TitleView extends FrameLayout {
- private Button leftButton;
- private TextView titleText;
- public TitleView(Context context, AttributeSet attrs) {
- super(context, attrs);
- LayoutInflater.from(context).inflate(R.layout.title, this);
- titleText = (TextView) findViewById(R.id.title_text);
- leftButton = (Button) findViewById(R.id.button_left);
- leftButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- ((Activity) getContext()).finish();
- }
- });
- }
- public void setTitleText(String text) {
- titleText.setText(text);
- }
- public void setLeftButtonText(String text) {
- leftButton.setText(text);
- }
- public void setLeftButtonListener(OnClickListener l) {
- leftButton.setOnClickListener(l);
- }
- }
第三步:在佈局文件中引用自定義的View文件
代碼出處:http://blog.csdn.net/guolin_blog/article/details/17357967
[html] view plaincopy
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <com.example.customview.TitleView
- android:id="@+id/title_view"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- </com.example.customview.TitleView>
- </RelativeLayout>
這樣就成功將一個標題欄控件引入到佈局文件中了,運行一下程序,效果如下圖所示: