How to generate id in android randomly and programmatically?

20.3k Views Asked by At

I'm trying to generate random ids for views as shown in following screenshot. But it didn't work. It got null. How should I findViewById ?

enter image description here

6

There are 6 best solutions below

0
On BEST ANSWER

use textView.setId(View.generateViewId()) introduced in API 17.

0
On

I got my own solution... It should be like that..

Random r = new Random();
    randomNo = r.nextInt(1000+1);

    TextView textView = new TextView(this);
    textView.setId(randomNo);
    linearLayout.addView(textView);
    int childCount = linearLayout.getChildCount();
    for(int i=0;i<childCount;i++){
        if(linearLayout.getChildAt(i).getId()==randomNo){
            TextView cloneTextView = (TextView) linearLayout.getChildAt(i);
            cloneTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
            cloneTextView.setText("I'm a clone...!");
            linearLayout.removeAllViews();
            linearLayout.addView(cloneTextView);
        }
    }

It works and that's what I want. Thank you all.

2
On
 TextView tv = new TextView(this);

This means you're creating the TextView dynamically. So you don't need to do findViewById. findViewById is used when the view with id is present in xml file.

Remove the TextView cloneTextView = (TextView) findViewById(randomNo) line. Your question is vague, I tried to explain.

2
On

You can create UUID (universal unique identifier) as follow :

String id= UUID.randomUUID().toString();
0
On

Best practices for unique identifiers

Java

String uniqueID = UUID.randomUUID().toString();

Kotlin

var uniqueID = UUID.randomUUID().toString()
0
On

Something like this may work.

But I'm not sure about possible performance and memory issues, since it will return an instance of a view (if found). During a little test sequence it never hit an existing id, with other words the first random number was always ok.

private int createUniqueId() {

    int id = RandomUtils.nextInt();

    while(findViewById(id) != null) {
        //id is not unique, try another one...
        id = RandomUtils.nextInt();
    }
    //return unique id
    return id;
}