如何以编程方式为视图分配 ID? [英] How can I assign an ID to a view programmatically?

查看:37
本文介绍了如何以编程方式为视图分配 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个 XML 文件中,我们可以像 android:id="@+id/something" 这样的视图分配一个 ID,然后调用 findViewById(),但是以编程方式创建视图时,如何分配 ID?

In an XML file, we can assign an ID to a view like android:id="@+id/something" and then call findViewById(), but when creating a view programmatically, how do I assign an ID?

我认为 setId() 与默认分配不同.setId() 是额外的.

I think setId() is not the same as default assignment. setId() is extra.

有人可以纠正我吗?

推荐答案

Android id 概览

Android id 是一个常用于标识视图的整数;这个 id 可以通过 XML(如果可能)和通过代码(以编程方式)分配.id 对于获取 XML 定义的 ViewInflater 生成的 code>(例如使用 setContentView.)

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

  • android:id="@+id/somename" 的属性添加到您的视图中.
  • 构建应用程序时,android:id 将被分配一个唯一 int 以在代码中使用.
  • 使用R.id.somename"(实际上是一个常量)在代码中引用您的 android:idint 值.
  • 这个int可以随构建而变化所以永远不要从gen/package.name复制id/R.java,只需使用R.id.somename".
  • (此外,当 Preference 生成其 View 时,不使用在 XML 中分配给 Preferenceid>.)
  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)
  • 使用someView.setId(int);
  • 手动设置ids
  • int 必须是正数,否则是任意的 - 它可以是任何你想要的(如果这很可怕,请继续阅读.)
  • 例如,如果创建和编号表示项目的多个视图,您可以使用它们的项目编号.
  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.
  • XML 分配的 id 将是唯一的.
  • 代码分配的id不必必须是唯一的
  • 代码分配的 ids 可以(理论上)与 XML 分配的 ids 冲突.
  • 如果查询正确,这些冲突的 id 无关紧要(继续阅读).
  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).
  • findViewById(int) 将从您指定的视图中递归地遍历视图层次结构,并返回它找到的第一个 View具有匹配的 id.
  • 只要在层次结构中在 XML 定义的 id 之前没有分配代码的 idfindViewById(R.id.somename) 将始终返回 XML 定义的视图,因此 id 'd.
  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.
  • 在布局 XML 中,使用 id 定义一个空的 ViewGroup.
  • 例如带有 android:id="@+id/placeholder"LinearLayout.
  • 使用代码用 Views 填充占位符 ViewGroup.
  • 如果需要或想要,为每个视图分配任何方便的 id.
  • 使用 placeholder.findViewById(convenientInt); 查询这些子视图;

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

API 17 引入了 View.generateViewId(),它允许您生成唯一 ID.

API 17 introduced View.generateViewId() which allows you to generate a unique ID.

如果您选择保留对视图的引用,请务必使用 getApplicationContext() 实例化它们,并确保在 中将每个引用设置为 nullonDestroy.显然,泄漏Activity(在被销毁后挂在上面)是一种浪费.:)

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

API 17 引入 View.generateViewId() 它生成一个唯一的 ID.(感谢 take-chances-make-changes 的指向这个出来.)*

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

如果您的 ViewGroup 不能通过 XML 定义(或者您不希望它被定义),您可以通过 XML 保留 id 以确保它保持唯一:

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

这里,values/ids.xml 定义了一个自定义的id:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

然后一旦创建了 ViewGroup 或 View,您就可以附加自定义 id

myViewGroup.setId(R.id.reservedNamedId);

冲突的 id 示例

为了通过混淆示例的方式清晰起见,让我们检查在幕后存在 id 冲突时会发生什么.

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/placeholder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
</LinearLayout>

为了模拟冲突,假设我们最新的构建分配了 R.id.placeholder(@+id/placeholder) 和 int 12..

接下来,MyActivity.java 以编程方式(通过代码)定义了一些添加视图:

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
    TextView tv = new TextView(this.getApplicationContext());
    // One new TextView will also be assigned an id==12:
    tv.setId(i);
    placeholder.addView(tv);
}

所以 placeholder 和我们新的 TextView 之一的 id 都是 12!但是如果我们查询占位符的子视图,这并不是真正的问题:

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
 placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12: 
Activity.this.findViewById(12);

*还不错

这篇关于如何以编程方式为视图分配 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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