Zin Win Htet
Zin Win Htet

Reputation: 2565

How to generate id in android randomly and programmatically?

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

Upvotes: 6

Views: 21512

Answers (6)

Abdul Basit Rishi
Abdul Basit Rishi

Reputation: 2425

Best practices for unique identifiers

Java

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

Kotlin

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

Upvotes: 4

Osama Ibrahim
Osama Ibrahim

Reputation: 1021

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

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

Upvotes: 0

Montassir Ld
Montassir Ld

Reputation: 561

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

Upvotes: 20

Dirk
Dirk

Reputation: 2051

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;
}

Upvotes: 0

Zin Win Htet
Zin Win Htet

Reputation: 2565

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.

Upvotes: 0

Aniruddha
Aniruddha

Reputation: 4487

 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.

Upvotes: 2

Related Questions