Android----xml文件中的控件的id设置

发布时间:2020-07-14 12:32:54 作者:wauoen
来源:网络 阅读:4910

    Android开放中要想得到布局文件中控件的引用,该控件必须设置id属性,这两有两种方式设置id:(1)@+id/xxxx;(2)@id/xxxx;下面做个简单的介绍。

  1. @+id/xxx:如果R文件中没有该id则创建;

注意:一个xml文件中不能出现两个以该形式设置同一id的两个控件(include标签例外);

示例1 正确的使用:

<TextView
    android:id="@+id/mytv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello world"/>

示例2 错误(两个id相同):此时系统会提醒报错

<TextView
    android:id="@+id/mytv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello world"/>
<TextView
    android:id="@+id/mytv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello world"/>

示例3 允许以下用法,但是该id指向的是include标签,之后的linearLayout设置id的操作无意义:

<include
    android:id="@+id/include1"
    layout="@layout/my"
    android:layout_width="50dp"
    android:layout_height="50dp"/>
<LinearLayout
    android:id="@+id/include1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"/>

如果将include标签与LinearLayout交换位置则会报错。

示例 4 允许以下用法,但是该id指向TextView,之后的include标签和LinearLayout设置id无意义:

<TextView
    android:id="@+id/mytv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello world"/>
<include
    android:id="@id/mytv"
    layout="@layout/my"
    android:layout_width="50dp"
    android:layout_height="50dp"/>
<LinearLayout
    android:id="@id/mytv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"/>

如果将TextView的位置下移,运行会出错。如果include中引用的布局存在与TextView相同的id设置,不会报错但是无意义。

2.@id/xxxx:引用ids.xml中相应的id,与@+id/xxx不同,一旦向ids.xml文件中添加一个id在R.java文件中会生成一个相应的id,无论是否有控件使用该id。

使用示例:

(1)创建ids.xml

<resources>
    <item name="hello" type="id" />
    <item name="hello2" type="id" />
    <item name="hello3" type="id" />
    <item name="hello4" type="id" />
    <item name="hello5" type="id" />
    <item name="hello6" type="id" />
    <item name="hello7" type="id" />
    <item name="hello8" type="id" />
</resources>

(2)使用id

<TextView
    android:id="@id/hello"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello 1" />

<TextView
    android:id="@id/hello"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello 2" />

<TextView
    android:id="@id/hello"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello 3" />

多个控件可以以同样的方式设置统一id,但是该id只属于最先使用该id的控件。

推荐阅读:
  1. 设置控件某个地方的圆角属性
  2. android 设置控件的字体

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

标签 include android

上一篇:opengl 在winCE系统的使用

下一篇:Office365之Exchange混合部署后更改已迁移到云上用户邮箱地址

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》