Mark F
Mark F

Reputation: 1543

Dynamically Set ID to a Button in Android

I want to dynamically create a button but am having an issue when it comes to setting an ID for it. I tried putting an integer value in there but keep getting an error that says "Expected Resource of Type ID." The issue is that I DONT want to create this Button in my XML file and yet I need a way to track it with an ID. Please Help.

Button changeButton = new Button(getApplicationContext());
changeButton.setText("Change");
changeButton.setId(1);//Keep Getting an error here

Upvotes: 7

Views: 16591

Answers (2)

Flavius P.
Flavius P.

Reputation: 547

In your res/values folder you can keep an ids.xml file, where you can define:

<resources>
   <item type="id" name="your_button_id"/>
   ...
</resources>

Then, you can use it in your code:

changeButton.setId(R.id.your_button_id);

Upvotes: 15

iTurki
iTurki

Reputation: 16398

If your goal is to track it, you could try setTag:

 changeButton.setTag("any_tag");

Notice that the tag is of type Object, meaning it could be any object you want (String, int, Date, CustomeObject, ...etc).

Upvotes: 8

Related Questions