Home > OS >  Why can't we set string ID to a view programmatically in Android?
Why can't we set string ID to a view programmatically in Android?

Time:12-17

<WebView android:id="@ id/googleWebview"/>

Here I can set an ID as the string "googleWebview" but if I try to use setId() programatically it expects an integer. Why is this?

CodePudding user response:

In Android all view IDs are integers - @ id/googleWebView is just a label for an integer ID.

In this case the @id/ indicates that it's handling an ID reference, the means that this is a new ID that should be generated. Under the hood, Android stores these generated IDs in the R file, and you can access reference them programmatically as R.id.{label}.

CodePudding user response:

When the app is build "@ id/googleWebview" is actually turned into an int. It will go to the R class. To access any ids you defined before in your xml files you can simply write R.id.idName in your code so in your case:

view.setId(R.id.googleWebview);

for example

  • Related