2
<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?

Henry Twist
  • 5,666
  • 3
  • 19
  • 44
  • The question is also. Why do you want to set an id at all? Is it only to find it again later? In that case you might want to use `setTag` instead of `setId`. Tags can be any object, including strings. And you can check a view's tag easily with `getTag` or search for them with `findViewWithTag` instead of `findViewById` – Ivo Dec 17 '21 at 09:53
  • ohh i dont know about setTag, will check it up thanks!! – MOHAMED SIKKANDAR AFZAL M Dec 17 '21 at 11:10

2 Answers2

2

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

Henry Twist
  • 5,666
  • 3
  • 19
  • 44
  • thanks , if am webview programatically which is not used in XML and i need to set id as string? is it possible? or do i need to generate unique id and set to it? – MOHAMED SIKKANDAR AFZAL M Dec 17 '21 at 09:37
  • 2
    If it's not declared in XML at all then you can generate an ID - https://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts. However I don't see many use cases for this. – Henry Twist Dec 17 '21 at 09:39
0

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

Ivo
  • 18,659
  • 2
  • 23
  • 35