自定义控件简介

带悬停标题的ExpandableListView是自定义控件,在实现复杂的代码之前,先了解下自定义控件,并通过一个简单的自定义控件来加深理解。

1. 自定义View的步骤

  1. 布局
    • 自定义View的属性
    • XML或Java代码控制布局
      • 测量——onMeasure(int,int)(该函数可重写可不重写,具体看需求)
      • 布局——onLayout(boolean,int,int,int,int)
      • 绘制——onDraw(Canvas canvas)
  2. 处理逻辑
    • 构造函数(获得View属性值,初始化等)
    • 自定义处理逻辑
    • 事件响应(onClickonScroll等)
  3. 提供数据(数据和处理逻辑分开,Adapter)
  4. 使用
    • layout
    • Activity

2. Android自定义控件的三种实现方法

  1. 组合原生控件(用到的步骤最少)
  2. 自己绘制(用到的步骤最多)
  3. 继承原生控件

3. 组合原生控件

将自己需要的控件组合成一个新控件步骤如下:

3.1 布局

创建一个由控件组合成的布局
eg.view_top.xml使用RelativeLayout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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="wrap_content"
android:orientation="vertical"
android:padding="10dp">

<ImageView
android:id="@+id/top_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_drop_up" />
...
</RelativeLayout>

3.2 处理逻辑

自定义View控件继承该布局控件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class TopView extends RelativeLayout{
public TopView(Context context, AttributeSet attrs) {
super(context, attrs);
// 加载布局
LayoutInflater.from(context).inflate(R.layout.view_top, this);
// 获取组合控件
top_left = (ImageView) findViewById(R.id.top_left);
...
}

// 为左侧返回按钮添加自定义点击事件
public void setOnclickLeft(OnClickListener listener) {
top_left.setOnClickListener(listener);
}
}

3.3 使用

3.3.1 layout中使用

1
2
3
4
<com.example.TopView
android:id="@+id/top_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

3.3.2 在MainActivity中使用

MainActivity中对控件做操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private TopView topView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topView = (TopView) findViewById(R.id.top_view);

topView.setOnclickLeft(new View.OnClickListener() {
@Override
public void onClick(View view) {
...
}
});

4. 自己绘制控件

此部分内容较多,详细可参见另一篇文章

自己绘制控件

5. 继承原生控件

6. 参考文献

Android自定义控件的三种实现方式
Android自定义控件View(一)
自定义控件详解(五):onMeasure()、onLayout()
Android 自定义 view(四)—— onMeasure 方法理解
ANDROID自定义视图——onMeasure,MeasureSpec源码 流程 思路详解
ANDROID自定义视图——onLayout源码 流程 思路详解