android TextView 动态设置id 引用ids.xml

3 篇文章 0 订阅
2 篇文章 0 订阅

引用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的控件。

java 中根据“hello”字符串获取

int tvid = getResources().getIdentifier("hello", "id", mContext.getPackageName());

注:第二个参数写"id"与写"string"结果不一样

 

 

int itemId = getResources().getIdentifier("item_i_1", "layout", mContext.getPackageName()); 这样可直接获取layout文件下xml 的id
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值