Create a new layout title.xml
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:background= "@drawable/title_bg" > <ButtonAndroid:id= "@+id/title_back"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_margin= "15dip"Android:background= "@drawable/back_bg"Android:text= "Back"Android:textcolor= "#fff" /> <TextViewAndroid:id= "@+id/title_text"Android:layout_width= "0dip"Android:layout_height= "Wrap_content"android:layout_gravity= "Center"Android:layout_weight= "1"android:gravity= "Center"Android:text= "Title Text"Android:textcolor= "#fff"android:textsize= "24SP"/> <ButtonAndroid:id= "@+id/title_edit"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center"Android:layout_margin= "15dip"Android:background= "@drawable/edit_bg"Android:text= "Edit"Android:textcolor= "#fff"/> </LinearLayout>
New Titlelayout inherits LinearLayout, let him become our custom title bar control, the code is as follows:
Packagecom.zhangbz.uicustomviews;Importandroid.app.Activity;ImportAndroid.content.Context;ImportAndroid.util.AttributeSet;ImportAndroid.util.Log;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.widget.Button;Importandroid.widget.LinearLayout;ImportAndroid.widget.Toast; Public classTitlelayoutextendsLinearLayout { PublicTitlelayout (Context context, AttributeSet attrs) {Super(context, attrs); Layoutinflater.from (context). Inflate (R.layout.title, This); }}
Overrides the constructor, which is called when the control is introduced into the layout.
Modify Activity_main.xml To add this custom control to the layout file:
< com.zhangbz.uicustomviews.TitleLayout Android:layout_width = "Match_parent" android:layout_height= "Wrap_content" ></ Com.zhangbz.uicustomviews.TitleLayout >
Note: The full class name should be used here.
Register the Click event for the button in the title bar in the Titlelayout.java file:
Button Titleback =(Button) Findviewbyid (r.id.title_back); Button Titleedit=(Button) Findviewbyid (R.id.title_edit); Titleback.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {(Activity) GetContext ()). Finish (); } }); Titleedit.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {toast.maketext (GetContext (),"You clicked Edit button", 0). Show (); } });
Android Create custom controls