如何分配唯一的ID,以动态创建的意见? [英] How to assign unique ids to dynamically created Views?

查看:198
本文介绍了如何分配唯一的ID,以动态创建的意见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我创建浏览 - 在这种情况下,的EditText - 动态。但是,每一个查看我补充需要有一个唯一的ID。

In my app I am creating Views - in this case an EditText - dynamically. But every View I add needs to have a unique id.

EditText editText = new EditText(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
editText.setLayoutParams(params);

// Which value am I supposed to use here?
editText.setId(value);

layout.addView(editText);

我害怕冲突,如果我给你一个随机值,我想不出任何方法来生成的ID不冲突的可能性。

I am afraid of conflicts if I assign a random value and I cannot think of any way to generate ids without the possibility of conflicts.

请注意,我知道,可以定义一组固定在RES /价值/ ids.xml的ID,但是这不是我想要的!我需要动态地创建IDS!我不知道我需要多少。

Please not that I know that one can define a fixed set of ids in res/values/ids.xml, but that is not what I want! I need to create the ids dynamically! I have no idea how many I need.

那么,有没有安全的方法来生成IDS?

So is there any safe way to generate ids?

推荐答案

  • 手动设置 ID s,使用 someView.setId( INT );
  • INT 必须是积极的,但另有arbitrary-它可以是任何你想要的(请继续阅读,如果这是可怕的。)
  • 例如,如果要创建和编号若干意见重新presenting项目,你可以用他们的项目编号。

Assign id via code (programmatically)

  • 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.
  • 要分配ID -

    To assign id -

    for(int i =0 ; i < yourIDcount ; i++){
        yourView.setId(i);
    }
    

    要获得ID -

    To get id -

    View.findViewById(yourView.getId());
    

    此外,

    API 17 推出 View.generateViewId()生成一个唯一的ID。

    API 17 introduced View.generateViewId() which generates a unique ID.

    检查:

    Check:

    <一个href="http://stackoverflow.com/questions/8460680/how-can-i-assign-an-id-to-a-view-programmatically">how-can-i-assign-an-id-to-a-view-programmatically和<一href="http://stackoverflow.com/questions/10261190/android-assign-and-retrieve-ids-dynamically">android-assign-and-retrieve-ids-dynamically.

    这篇关于如何分配唯一的ID,以动态创建的意见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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