Veer Shrivastav
Veer Shrivastav

Reputation: 5496

Dynamic element Id to setId(int) - Android

I saw the syntax definition of setId(int) and findViewByID(int).

But how we use findViewById(R.id.row1)

I tried using this:

Object1.setId(Integer.parseInt("repeat"));

It showed no error but dint run too.

What is wrong? If setId(int) takes int and and passing integer to it, then what is the error. When I commented the statement the program runs.

and if findViewById(int) accepts integers then is R.id.object_id is an integer? if yes, how is it mapped with the findViewById()? if No, then how to use findViewById and setId.

Upvotes: 0

Views: 1364

Answers (3)

Arash GM
Arash GM

Reputation: 10395

It's not recommended to set your object id yourself , findViewById make access to your R class that contains pointers to your XML items id.

when you define an id in your Xml Layout file like

android:id="@+id/txtyourId"

in compile time compiler create a reference to your XML Item layout in R class that you can access it from your java code by findViewById

View YourItem = (View)this.findViewById(R.id.txtyourId);

Upvotes: 1

user1969053
user1969053

Reputation: 1760

You can define your Ids as resources and then use setId() of the view to set it.

Upvotes: 0

bongo
bongo

Reputation: 763

You can use setId(int) only for objects extending View class.

Upvotes: 0

Related Questions