Android自定义控件----初级 实现多个Activity复用同个自定义控件

一步一步详细介绍自定义控件的开发流程。
这边介绍一个最为原始的自定义控件demo------多个activity共用某个自定义控件。
主要步骤如下:
1.编写自定义控件的layout文件;
2.实现自定义控件的动作;
3.在需要添加自定义控件的activity的layout中加入自定义控件。

接下来按步骤一步一步实现。

  1. 自定义控件Layout文件 : customui.xml
    layout中主要是添加了两个button, 等会在对应的实现类中会有响应的事件响应。
<?xml version="1.0" encoding="utf-8"?>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/delete"
    android:text="delete"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/add"
    android:text="add"/>

2.实现类 – customui.java
该实现类主要是注册了两个button事件,并且对其作出响应。
这边需要注意的是代码中加粗的一段,LayoutInflater可以用于加载布局文件。
1)对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2)对于一个已经载入的界面,我们就可以使用Activiyt.findViewById()方法来获得其中的界面元素。

package com.example.customui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class customui extends LinearLayout {
Button add, delete;
public customui(Context context, AttributeSet attrs) {
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.customui,this);
add = (Button)findViewById(R.id.add);
delete = (Button)findViewById(R.id.delete);
add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), “You clicked add button”,
Toast.LENGTH_SHORT).show();
}
});
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), “You clicked delete button”,
Toast.LENGTH_SHORT).show();
}
});
}
}

3.在需要添加自定义控件的activity的layout中加入自定义控件。
我这边有两个Activity,这两个Activity都是用了同一个自定义控件。
在主Activity的layout中加入自定义layout, 用包名加类名加入xml中。

<?xml version="1.0" encoding="utf-8"?>

<com.example.customui.customui
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/customui"
    tools:ignore="MissingConstraints">
</com.example.customui.customui>

<Button
    android:id="@+id/change"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="change"
    tools:ignore="MissingConstraints" />

另一个Activity也是以同样的方式加入自定义控件。

源码位置:https://download.csdn.net/download/fuhonghui12345/11191140


版权声明:本文为fuhonghui12345原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。