以编程方式将 id 添加到 R.id [英] programmatically add id to R.id

查看:38
本文介绍了以编程方式将 id 添加到 R.id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 EditText 对象,然后我尝试在单元测试中引用它.为这个动态创建的对象向 R.id 添加新的 id 的最佳方法是什么,以便我以后可以通过 findViewById()在单元测试中?

I am creating an EditText object which I then try to reference in a unit test. What is the best way to add a new id to R.id for this dynamically created object, so that I can later reference it via findViewById() in the unit test?

推荐答案

您可以使用 xml 资源文件设置稍后将在 R.id 类中使用的 ID,并让 Android SDK 在编译时为它们提供唯一值.

You can set ID's you'll use later in R.id class using an xml resource file, and let Android SDK give them unique values during compile time.

res/values/ids.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="my_edit_text_1" type="id"/>
    <item name="my_button_1" type="id"/>
    <item name="my_time_picker_1" type="id"/>

</resources>

在代码中使用它:

myEditTextView.setId(R.id.my_edit_text_1);

这篇关于以编程方式将 id 添加到 R.id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆