简体   繁体   English

在xml布局中为View元素重用ID字符串

[英]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. 我有一个具有掌上电脑layout.xml和平板电脑layout.xml的应用程序。 Inside the layout.xml a fragment is declared like this: 在layout.xml内部,片段声明如下:

<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. 为了使事情保持简单,可以说此layout.xml在res / layout和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. 这在平板电脑上正常工作,但是当我尝试在手持设备上运行时,myFrag为空。 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. 玩了一会儿之后,我发现如果我将掌上电脑layout.xml中的名称更改为myFrag2并搜索该名称,它将起作用。 What confuses me is that according to the Android documentation, I should be able to reuse this id: 令我困惑的是,根据Android文档,我应该能够重用此ID:

http://developer.android.com/guide/topics/ui/declaring-layout.html#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... 我真的不想写代码来测试myFrag是否为空,然后尝试加载掌上电脑名称...

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. 据我所知,如果您将使用res / layout-large,则不得将res / 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. 我无法确切地说出原因,但似乎R没有得到正确的重新生成。 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. 我消灭了它并对其进行了重新生成,整个世界一切都很好,所以看起来好像没有什么特别的事情发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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