学习android随手记 之 android:name android:id

来源:互联网 发布:舒畅 天山童姥 知乎 编辑:程序博客网 时间:2024/06/15 16:03

android:name  android:id 这两个属性在我们编辑xml文件中常用到(不知道表达为属性准不准确)


今天博主在写代码时,遇到了 Button bt=(Button)findViewById(R.XXX.closeServ);返回的bt 一直为NULL;


刚开始也不知道是null,结果刚安装到手机,屏幕一跳直接就关了。


然后再logcat中找到null,作为一个低级的程序员就请教了度娘。

网上给出几种解答(eclipse开发环境):

1.project 勾选自动生成

2.project -》 clean

3.xml中资源名字中不能有大写(PS:我感觉挺扯淡)

4.检查R文件是不是自己工程的

5.........

--------------------------------------------------------------------

最后统统没法解决,但是错误十分奇怪,因为有一个按钮不是null,其他的都是null;


我先写一下xml的部分内容,大神看了轻喷(斜杠方向可能会错,纯手打)~

<Button 

android:id="@+id/startServ"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="开启服务"

/Button>

<Button 

android:name="@+id/closeServ"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="关闭服务"

/Button>

<Button 

android:name="@+id/c"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="多一个按钮"

/Button>

------------------------------------------------------------------------


那么在java文件中我们按照一般套路用Button start=(Button)findViewById(R.id.startServ);

         Button close=(Button)findViewById(R.id.closeServ);
Button c=(Button)findViewById(R.id.c);


结果呢。上面的程序就会编译通过,运行也没错。但是一旦注册监听器(例如:close.setXXXListener(this)),那么该行变回null对象进行操作。


那么为什么会错呢,编译都没错,套路也是这样啊,楼主真的找了一两个小时。

相信聪明的读者已经从标题中知道了答案,没错就是android:id android:name !

在上面的结果中,只有start按钮不是null,对比xml文件,start用的是android:id,其他用的是android:name.

正是这两个属性不同导致的错误。

下面,我们来仔细了解这两个属性。



------------------------------------------------------------------------------------------------------------------

android:id


下面关于android:id的内容来源于:
http://blog.163.com/android_2012/blog/static/209514187201261910219993/

不作详细转载,

简单来讲:

 @+id 新增一个资源id
 @id和android:id,引用现有的资源id


--------------------------------------------------------------------------------------------------------------------

android:name

引用1:
http://blog.csdn.net/aminfo/article/details/7918097

该文章中说android:name就是错误的,现在都是id。。。不多说了


引用2:

http://www.cnblogs.com/yaozhongxiao/archive/2013/10/14/3368706.html

引用3:
http://38275.blog.51cto.com/28275/707914/

以上两个引用并不在说两个属性的不同,而只是在讲android:name属性。

我们仔细可以发现,android:name属性存在于AndroidManifest.xml文件中。


------------------------------------------------------------------------------

so,不知道能不能蹩脚的总结:

android:id属性用在写Activity的布局文件中

android:name属性用在AndroidManifest.xml文件中


至于具体解释,低能的楼楼继续翻书去了,各位路过的父老乡亲们有指导意见大可留言~

Button close=(Button)findViewById(R.id.closeServ);
Button close=(Button)findViewById(R.id.closeServ);
0 0
原创粉丝点击