Gnuey Gnuey - 3 months ago 7
Android Question

Are view ids local to the activity context?

What is the scope of the a view's identifier?

Is it local to its corresponding activity?

For example, if in activity_main.xml I specify

<EditText android:id="@+id/edit_message" />


Within my DisplayMessageActivity.java would I legally be able to access
R.id.edit_message
?

When I test this I get an exception, but none of the messages are clearly telling me it's due to accessing an "id out of context", or something along those lines. I'm getting errors like
java.lang.NullPointerException


This question arose as I was following the beginner tutorial:

https://developer.android.com/training/basics/firstapp/building-ui.html



EDIT
Thanks both for clarifying the difference between the scope of
R.id
and that of the widget with id
R.id.edit_message
(in terms of accessing it by
fiewViewById()
).

I actually intended to ask "would I be able to call findViewById(R.id.edit_message) in Activity A to access a widget in Activity B". And from your answers it appears the answer to that question is "no".

In my code, I did not include a view with id
R.id.edit_message
in the ViewGroup of Activity B. That's probably why I got the errors.

Answer

What is the scope of the a view's identifier?

The identifier is an integer. It does not have a scope.

Within my DisplayMessageActivity.java would I legally be able to access R.id.edit_message?

If we assume that you mean "would I be able to call findViewById(R.id.edit_message) to access a widget?", you can certainly call it. Whether you get null or not will depend on whether the activity has a widget in its view hierarchy with that ID.

However, Activity A cannot call findViewById() to retrieve a widget from Activity B. The id is an integer and has no scope. However, findViewById() has a scope: the view hierarchy of whatever you call it on (e.g., an activity, a ViewGroup).

Comments