5

Can id resources refer to an element later in the file?

Here I have two fields, one for the username, and another for the password. I create a new ID resource (with the @+id/ syntax) for the password field, but the username field cannot find it in the android:nextFocusDown field. I have omitted other fields from the layout xml, because they aren't relevant.

How would I need to declare the IDs in this case?

<EditText
    android:id="@+id/login_username"
    android:nextFocusDown="@id/login_password" />

<EditText
    android:id="@+id/login_password"
    android:nextFocusUp="@id/login_username"
    android:nextFocusDown="@id/login_submit" />

Building with gradle, I'm getting an error that looks like this: Error:(41, 32) No resource found that matches the given name (at 'nextFocusDown' with value '@id/login_password').

I do not get an error for android:nextFocusUp="@id/login_username" field, which leads me to believe you must declare the id before you use it.

I also get compile errors in my code, because no R.java file is being generated, most likely because the resources it builds from aren't building either.

With all the fancy build tools in android, I'm surprised this is a problem. Is this a known problem or desired behavior?

pensono
  • 336
  • 6
  • 17
  • 2
    The resource compiler does not look forward, simply @+id in the first place that uses that id, even if not an "id" field – zapl Oct 31 '14 at 05:19

2 Answers2

6

You can specify a @+id in the first value

<EditText
    android:id="@+id/login_username"
    android:nextFocusDown="@+id/login_password" />
<EditText
    android:id="@+id/login_password"
    android:nextFocusUp="@id/login_username"
    android:nextFocusDown="@id/login_submit" />

There is no harm to having multiple @+id's around. It could make detecting typos a bit more difficult, but if you need it, it'll work well.

PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
  • Great answer. To avoid the downside of potential typo as you pointed out, one could omit "+" for the second id so that only one "+" for each id. – Hong Dec 12 '16 at 15:23
4

you can pre-generate some ids by creating file values/ids.xml with something like this

<resources>
    <item name="login_password" type="id"/>
</resources>

Here is your case https://stackoverflow.com/a/12247971/4178124

Community
  • 1
  • 1
Dmitry
  • 864
  • 7
  • 15