Android中创建自定义控件
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>