前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android自定义组合控件的过程

Android自定义组合控件的过程

作者头像
张拭心 shixinzhang
发布2022-11-30 16:22:40
3750
发布2022-11-30 16:22:40
举报

自定义组合控件的过程:

(1)自定义一个View,并且继承一种布局,一般来说是相对或者线性布局

(2)实现父类的(3个)构造方法,通常需要在每个构造方法中调用自定义的初始化布局方法(比如那个initView方法,这个方法需要将我们组合控件的那个布局文件转换成一个View,并且加载到自定义的View; 然后将要操作到的控件实例化)

private void iniView(Context context) {

//将制定的布局文件转换成一个View,并且加载到SettingItemView

View.inflate(context, R.layout.setting_item_view, this);

cb_states = (CheckBox) findViewById(R.id.cb_states);

tv_title = (TextView) findViewById(R.id.tv_title);

tv_desc = (TextView) findViewById(R.id.tv_desc);

}

(3)根据需要定义一些操作控件的API方法,比如之前的那个public void setChecked(boolean checked)等

(4)根据需要,自定义控件的属性,可以参照TextView属性

(5)首先,参照xmlns:android="http://schemas.android.com/apk/res/android"

自定义一个命名空间

xmlns:XXX="http://schemas.android.com/apk/res/包名"

例如:

xmlns:sxkeji="http://schemas.android.com/apk/res/com.example.mobilesafe"

(6)在res/values/attrs.xml中创建我们的属性:

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

<resources>

<declare-styleable name = "TextView">

<attr name="title" format="string"/>

<attr name="desc_on" format="string"/>

<attr name="desc_off" format="string"/>

</declare-styleable>

</resources>

(7)在布局文件中使用自定义属性:

<com.sxkeji.mobilesafe.ui.SettingItemView

sxkeji:title="设置自动更新"

sxkeji:desc_on="自动升级已经开启"

sxkeji:desc_off="自动升级已经关闭"

android:id="@+id/siv_update"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

/>

(8)在我们自定义控件的View的、带有2个参数的构造函数中,利用attrs.getAttributeValue()方法取出属性值,关联布局文件中对应的控件

例如:

String title =  attrs.getAttributeValue("http://schemas.android.com/apk/res/com.example.mobilesafe", "title");

tv_title.setText(title);

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-03-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档