编程意见如何设置唯一的ID? [英] Programmatic Views how to set unique id's?

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

问题描述

我创建我的应用程序一堆纲领性查看秒。因为它似乎是他们都在默认情况下具有相同的 ID = -1 。为了与他们合作,我需要生成唯一的ID。

I am creating in my app bunch of programmatic Views. As it appeared to be they all by default have the same id=-1. In order to work with them I need to generate unique id's.

我尝试了好几种方法 - 随机数的产生,并根据当前时间,但无论如何也没有100%的保证不同的看法会有不同的ID的

I have tried several approaches - random number generation and based on current time, but anyway there's no 100% guarantee that different Views will have different id's

只是想知道有没有更可靠的方式来生成唯一的吗?也许有特殊的方法/类?

Just wondering is there any more reliable way to generate unique ones? Probably there's special method/class?

推荐答案

创建一个单独的类,有一个原子整数。凹凸的整数,当你需要一个视图id返回值。

Create a singleton class, that has an atomic Integer. Bump the integer, and return the value when you need a view id.

该ID将成为您流程的执行过程中唯一的,但西港岛线复位时,你的进程将重新启动。

The id will be unique during the execution of your process, but wil reset when your process is restarted.

public class ViewId {

    private static ViewId INSTANCE = new ViewId();

    private AtomicInteger seq;

    private ViewId() {
        seq = new AtomicInteger(0);
    }

    public int getUniqueId() {
        return seq.incrementAndGet();
    }

    public static ViewId getInstance() {
        return INSTANCE;
    }
}

请注意,该ID可能不是唯一的,如果已经是具有IDS在视图'图'的看法。您可以尝试以数字开头即是Integer.MAX_VALUE,并减少而不是从1去它 - > MAX_VALUE

Note that the id might not be unique, if there already are views that have ids in the view 'graph'. You could try to start with a number that is Integer.MAX_VALUE, and decrease it instead of going from 1 -> MAX_VALUE

这篇关于编程意见如何设置唯一的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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