自定义控件


一.重要知识点

android:background //可以指定图片和颜色
getContext(),获取当前对象所在的Context

xml布局文件转为View对象:
LayoutInflater.from(context).inflate(R.layout.menu, this);

在xml不居中加载另一个xml布局:
<include layout="@layout/menu" />

二.自定义控件:

1.xml代码,menu.xml

<?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="50dp"
android:orientation="horizontal"
android:background="#D16B07">

<Button
android:text="返回"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@drawable/btn"
android:id="@+id/title_back"
/>

<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="标题"
android:gravity="center"/>

<Button
android:text="编辑"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@drawable/btn"
android:id="@+id/title_edit"
/>
</LinearLayout>


2.java代码,Menu.java:
public class Menu extends LinearLayout {

public Menu(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.menu, this);

Button back,edit;
back = (Button)findViewById(R.id.title_back);
edit = (Button)findViewById(R.id.title_edit);

back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});

edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "编辑", Toast.LENGTH_LONG).show();
}
});
}
}


3.控件引用
<com.example.packname.Menu
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</com.example.packname.Menu>

原文地址:https://www.cnblogs.com/itfenqing/p/6719796.html