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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值