文档章节

再也不信网上流传的方法了!!android创建组件的真正写法!

五杀联盟
 五杀联盟
发布于 2014/12/26 18:03
字数 1065
阅读 34
收藏 0

http://blog.csdn.net/jincf2011/article/details/6344678 气死我了 这货博客坑死大爷了大爷弄了两天各种毛病

一看官网原来这玩意儿不是这么写的

官网教程:

All of the view classes defined in the Android framework extendView. Your custom view can also extend View directly, or you can save time by extending one of the existing view subclasses, such as Button.

To allow the Android Developer Tools to interact with your view, at a minimum you must provide a constructor that takes a Context and an AttributeSet object as parameters. This constructor allows the layout editor to create and edit an instance of your view.

class PieChart extends View {
   
public PieChart(Context context, AttributeSet attrs) {
       
super(context, attrs);
   
}
}

Define Custom Attributes


To add a built-in View to your user interface, you specify it in an XML element and control its appearance and behavior with element attributes. Well-written custom views can also be added and styled via XML. To enable this behavior in your custom view, you must:

  • Define custom attributes for your view in a <declare-styleable> resource element

  • Specify values for the attributes in your XML layout

  • Retrieve attribute values at runtime

  • Apply the retrieved attribute values to your view

This section discusses how to define custom attributes and specify their values. The next section deals with retrieving and applying the values at runtime.

To define custom attributes, add <declare-styleable> resources to your project. It's customary to put these resources into a res/values/attrs.xml file. Here's an example of an attrs.xml file:

<resources>
   
<declare-styleable name="PieChart">
       
<attr name="showText" format="boolean" />
       
<attr name="labelPosition" format="enum">
           
<enum name="left" value="0"/>
           
<enum name="right" value="1"/>
       
</attr>
   
</declare-styleable>
</resources>

This code declares two custom attributes, showText and labelPosition, that belong to a styleable entity namedPieChart. The name of the styleable entity is, by convention, the same name as the name of the class that defines the custom view. Although it's not strictly necessary to follow this convention, many popular code editors depend on this naming convention to provide statement completion.

Once you define the custom attributes, you can use them in layout XML files just like built-in attributes. The only difference is that your custom attributes belong to a different namespace. Instead of belonging to thehttp://schemas.android.com/apk/res/android namespace, they belong tohttp://schemas.android.com/apk/res/[your package name]. For example, here's how to use the attributes defined for PieChart:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">
 
<com.example.customviews.charting.PieChart
     
custom:showText="true"
     
custom:labelPosition="left" />
</LinearLayout>

In order to avoid having to repeat the long namespace URI, the sample uses an xmlns directive. This directive assigns the alias custom to the namespace http://schemas.android.com/apk/res/com.example.customviews. You can choose any alias you want for your namespace.

Notice the name of the XML tag that adds the custom view to the layout. It is the fully qualified name of the custom view class. If your view class is an inner class, you must further qualify it with the name of the view's outer class. further. For instance, the PieChart class has an inner class called PieView. To use the custom attributes from this class, you would use the tag com.example.customviews.charting.PieChart$PieView.

Apply Custom Attributes


When a view is created from an XML layout, all of the attributes in the XML tag are read from the resource bundle and passed into the view's constructor as an AttributeSet. Although it's possible to read values from the AttributeSet directly, doing so has some disadvantages:

  • Resource references within attribute values are not resolved

  • Styles are not applied

Instead, pass the AttributeSet to obtainStyledAttributes(). This method passes back a TypedArray array of values that have already been dereferenced and styled.

The Android resource compiler does a lot of work for you to make calling obtainStyledAttributes() easier. For each <declare-styleable> resource in the res directory, the generated R.java defines both an array of attribute ids and a set of constants that define the index for each attribute in the array. You use the predefined constants to read the attributes from the TypedArray. Here's how the PieChart class reads its attributes:

public PieChart(Context context, AttributeSet attrs) {
   
super(context, attrs);
   
TypedArray a = context.getTheme().obtainStyledAttributes(
        attrs
,
        R
.styleable.PieChart,
       
0, 0);

   
try {
       mShowText
= a.getBoolean(R.styleable.PieChart_showText, false);
       mTextPos
= a.getInteger(R.styleable.PieChart_labelPosition, 0);
   
} finally {
       a
.recycle();
   
}
}

Note that TypedArray objects are a shared resource and must be recycled after use.

太长了是吧 简单说一下:

自定义组件NewView继承一个View类

重写构造函数

 public NewView(Context context) {
        this(context,null);
    }
 public NewView(Context context, AttributeSet attrs) {
        super(context, attrs);
}

为了专业一点 让xml文件能配置这个组件 ,需要在values下的attrs.xml中定义一下自定义组件的参数

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NewView">
        <attr name="pressedIcon" format="reference" />
        <attr name="buttonIcon" format="reference"/>
        <attr name="text" format="string"/>
        <attr name="iconSize" format="dimension"/>
        <attr name="textSize" format="dimension"/>
    </declare-styleable>
</resources>

reference 代表引用资源文件 string代表字符 color 代表颜色  dimension代表大小

好了现在可以在布局文件中引入这个组件了

        <com.xxx.app.view.NewView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:text="@string/main_one"
            app:iconSize="20dp"/>

app代表属性的namespace,如果用android studio的话

根元素加上

    xmlns:app="http://schemas.android.com/apk/res-auto"

如果是eclipse 需要替换成

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

然后我们在构造函数中处理这些传入的参数

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.NewView, 0, 0);
    try{
       CharSequence text = a.getText(R.styleable.NewView_text);
    }finally{
    a.recycle();
    }

取到的参数怎么处理 就不用说了哈


© 著作权归作者所有

上一篇: JFinal用Redis
下一篇: p3p
五杀联盟
粉丝 17
博文 6
码字总数 1412
作品 0
郑州
私信 提问
android 添加快捷方式后总是启动第一个activity

求助, apk文件安装后,启动apk, 首先启动A activity ,A activity自动跳转到B,在B中实现添加桌面快捷方式,点击home键,再点击apk图标, apk还是从A启动, 请问如果解决。点击home键...

人生的过客
2012/04/27
1K
1
使用聚合数据的接口进行的RxAndroid学习

Demo数据源是聚合数据的免费Api,地址:https://www.juhe.cn/ 配合Retrofit 完成数据请求 例子比较简单,没事使用什么复杂的操作符。 就是简单的网络数据获取。 一些常用的操作符大家可以参考...

白jian
2016/10/09
161
0
Activity启动过程源码分析

简书 编程之乐 转载请注明原创出处,谢谢! 根据上篇文章- Launcher源码浅析,我们知道点击Launcher某个图标后,会调用Launcher的startActivitySafely方法。 如下: Launcher最终调用了父类 ...

编程之乐
2017/11/16
0
0
【Android学习】使用聚合数据的接口进行的RxAndroid学习

最近学习RxJava,一直在看大神的文章。 RxJava 在 GitHub 主页上的自我介绍是 "a library for composing asynchronous and event-based programs using observable sequences for the Java V......

夜晚晚
2016/11/30
302
0
React Native在Android当中实践(五)——常见问题

React Native在Android当中实践(一)——背景介绍 React Native在Android当中实践(二)——搭建开发环境 React Native在Android当中实践(三)——集成到Android项目当中 React Native在A...

YangZC
2018/05/28
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Spring Boot 2 实战:使用 Spring Boot Admin 监控你的应用

1. 前言 生产上对 Web 应用 的监控是十分必要的。我们可以近乎实时来对应用的健康、性能等其他指标进行监控来及时应对一些突发情况。避免一些故障的发生。对于 Spring Boot 应用来说我们可以...

码农小胖哥
31分钟前
3
0
ZetCode 教程翻译计划正式启动 | ApacheCN

原文:ZetCode 协议:CC BY-NC-SA 4.0 欢迎任何人参与和完善:一个人可以走的很快,但是一群人却可以走的更远。 ApacheCN 学习资源 贡献指南 本项目需要校对,欢迎大家提交 Pull Request。 ...

ApacheCN_飞龙
42分钟前
3
0
CSS定位

CSS定位 relative相对定位 absolute绝对定位 fixed和sticky及zIndex relative相对定位 position特性:css position属性用于指定一个元素在文档中的定位方式。top、right、bottom、left属性则...

studywin
51分钟前
6
0
从零基础到拿到网易Java实习offer,我做对了哪些事

作为一个非科班小白,我在读研期间基本是自学Java,从一开始几乎零基础,只有一点点数据结构和Java方面的基础,到最终获得网易游戏的Java实习offer,我大概用了半年左右的时间。本文将会讲到...

Java技术江湖
昨天
5
0
程序性能checklist

程序性能checklist

Moks角木
昨天
7
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部