---
title: "自定义控件"
author: "jogickis"
date: "2013-12-16T10:57:36Z"
tags: ["Android", "XML", "控件"]
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2013-12-16T10:58:48Z"
id: 1990128
url: "https://jogickis.iteye.com/blog/1990128"
---

\[b]1、在res/values 文件下定义一个attrs.xml 文件.代码如下:\[/b] \[code="java"] \[/code] 注意：在xml中，可能不会出现提示，所以需要记住书写格式 属性attr中format的值有一下几种： "reference" //引用 ，表示用@drawable/ # ffffff等，所以基本上都需要加上这个 "color" //颜色 "boolean" //布尔值 "dimension" //尺寸值 "float" //浮点值 "integer" //整型值 "string" //字符串 "fraction" //百分数,比如200% 可以同时加多个，如：format = "reference|color" \[b]2、创建一个类MyView 集成LinearLayout,必须集成public MyView(Context context,AttributeSet attrs)方法 \[/b] \[code="java"] TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.mys); View titleView = LayoutInflater.from(context).inflate(R.layout.head, null); addView(titleView, new LayoutParams(LayoutParams.WRAP\_CONTENT, LayoutParams.WRAP\_CONTENT)); mIcon = (ImageView)titleView.findViewById(R.id.icon); mTitle = (TextView)titleView.findViewById(R.id.title); mIcon.setBackgroundResource(array.getResourceId(R.styleable.mys\_icon, -1)); mTitle.setText(array.getString(R.styleable.mys\_title)); \[/code] 获取里面属性用 名字_ 属性 连接起来就可以.TypedArray 通常最后调用 .recycle() 方法，为了保持以后使用该属性一致性！ \[b]3、在布局文件中使用该控件：\[/b] 首先一定要加入命名空间： xmlns:test ="http://schemas.android.com/apk/res/com.android.tutor" test是自定义的前缀，后面com.android.tutor是项目的包名 如： \[code="java"] \[/code]