简体   繁体   中英

Reusing ID string for View elements in xml layout

I've got an app that has a handheld layout.xml and a tablet layout.xml. Inside the layout.xml a fragment is declared like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:paddingTop="2dp"
              android:paddingBottom="2dp">

<fragment class="com.example.MyFrag"
          android:id="@+id/myFrag"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"/>
</LinearLayout>

For the same of keeping things simple, let's say that this layout.xml is identical in res/layout and res/layout-large.

In my main activity, I reference this fragment like this:

final myFrag = (MyFrag) getSupportFragmentManager().findFragmentById(R.id.myFrag);

This works fine for the tablet, but when I try to run on handheld, myFrag is null. After a little playing around I found that if I change the name in the handheld layout.xml to myFrag2 and search for that name instead, it works. What confuses me is that according to the Android documentation, I should be able to reuse this id:

http://developer.android.com/guide/topics/ui/declaring-layout.html#id

Am I doing something wrong? I really don't want to have to write code to test whether myFrag is null and then try loading the handheld name instead...

As far as I know if you will be using the res/layout-large then you must not use the res/layout default directory for a layout. So if you will be using screen sizes then you should use all (most) that you will be considering. So you will need to implement small, normal for handhelds. you can read the documentation regarding screen sizes here

Turns out this is a non-question. I couldnt say exactly why but it appears R was not being properly regenerated. I wiped it out and regenerated it and all was well with the world, so it looks like there's nothing special going on afterall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM