探索自定义View

![Uploading swipe_begin_512654.png . . .]
我们创建一个View的子类,在代码中使用它的。
下面介绍下Android Developer上给的示例。

<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>

当然这里省略了layout_width等。
但是当我在AndroidStudio这样写的时候,并不顺利,因为AndroidStudio完全没有给我代码提示和补全。当我强行进行了代码拷贝之后。然后,有红色的error。把截张图,大家感受一下。

2017-01-20-15-23-37.jpg

这就奇怪了。这可是官方文档啊~
AndroidStudio 有一个好用的地方。在xml里,把鼠标移动到红色波浪线所在的语句上,会有错误提示。它告诉你原因,辅助你定位和修复问题。
然后我就收到了这样的反馈。

2017-01-20-15-29-29.jpg

In Gradle projects, the actual package used in the final APK can vary; for example,you can add a .debug package suffix in one version and not the other. Therefore, you should not hardcode the application package in the resource; instead, use the special namespace http://schemas.android.com/apk/res-auto which will cause the tools to figure out the right namespace for the resource regardless of the actual package used during the build.

这句话的意思很简单,代码编译构建成apk后,最终在apk文件的包名可能与实际的包名是不一致的,比如:你可会在原始包名coma.b添加.debug后缀在某个版本上,这样apk中真正的包名就变成了com.a.b.debug。你的程序可能无法很好的工作。因此在资源文件中,不推荐使用硬编码的方式制定包名。
所以,我们还是乖乖地使用http://schemas.android.com/apk/res-auto作为命名空间。

Extras

上面讲了一堆废话(你不这样觉得吗),下面讲一下,作为静态内部类的的一个View 子类,如何在xml中使用。
假如你有这样一个类:

public class PieChart extends View {
//....构造方法省略
public static class PieView extends View{
//....构造方法省略
}
}

当你需要在xml中使用PieView这个类的时候,你会怎么写?
一开始我是这么写的:

<com.drolmen.viewstudydemo.views.PieChart.PieView
android:layout_width="match_parent"
android:layout_height="match_parent"/>

这么写就错啦,百思不得其解。最后看到一篇不错的博客,找到了正确的写法:

<view
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.drolmen.viewstudydemo.views.PieChart$PieView"/>

有两个重要的点:

  1. <view ... ,看到了吗,View是小写
  2. 内部类PieView使用$符号与主类连接
    如果你想了解更多,推荐翻一下这篇博客http://blog.csdn.net/gorgle/article/details/51428515
    如有错误,欢迎指正,谢谢~
swipe_begin.png
swipe_moving_1.png
swipe_moving_2.png
swipe_expand.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容