1.創建一個TitleLayout繼承LinearLayout:
//創建自定義控件
public class TitleLayout extends LinearLayout { private final Button titleBack; private final Button titleEdit; public TitleLayout(Context context, AttributeSet attrs) { super(context, attrs); //通過LayoutInflater的from方法可以創建出一個LayoutInflater對象,然后調用inflate()方法可以動態加載布局文件 LayoutInflater.from(context).inflate(R.layout.title,this); titleBack = (Button) findViewById(R.id.title_back); titleEdit = (Button) findViewById(R.id.title_edit); titleBack.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { ((Activity)getContext()).finish(); } }); titleEdit.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Toast.makeText(getContext(), "You clicked Edit button", Toast.LENGTH_SHORT).show(); } }); } }
2.在activity_main.xml中添加這個自定義控件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.itheima.album.uicustomviews.MainActivity"> <!--<include layout="@layout/title"/>--> <com.itheima.album.uicustomviews.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
