2011-11-03 58 views
1

我有多个布局使用相同的按钮id,在这种情况下是@ + id/button1,在运行时我充气布局并从他们给定的视图中单独抓取每个按钮。第一个按钮抓取得很好,但是使用findViewById(从拥有的视图而非活动调用)找不到相同给定ID的所有后续按钮。Widget不尊重ID参数

检查调试器中的按钮会显示后续按钮具有几乎相同的ID标签,但会增加1.看起来,如果预先存在ID的实例,则Android不会考虑XML文件给出的ID。是这样吗?如果是这样的话,我们如何才能在视图之间绑定按钮,我们是否需要为每个小部件提供全局唯一的ID?

+0

我不知道发生了什么,但删除布局并重新构建它似乎解决了问题。尽管原始问题是真实的,但我多次通过调试器。资源发生了某些变化,以及它们如何针对Android项目进行编译,导致XML文件与已部署资源之间的小部件ID不匹配。 – watcher278

回答

0

最终,每个按钮都有自己的static final int,我们可以调用唯一的ID,对吧?

是的,你应该给每个按钮它自己的ID ...并且你不应该命名按钮button1,button2等等。

2

在同一视图层次结构中同时存在的每个小部件应具有唯一的ID值。换句话说,欢迎您在应用程序布局中重复使用@+id/button1,但将多个视图用相同的ID扩展到相同的层次结构中可能会导致不明确。

它在某种程度上取决于您的实际布局是如何构建的,但您可以做的另一件事是解决一些不明确的问题,即从层次结构下方的不同视图调用findViewById()。例如,我可以创建如下单个布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <LinearLayout 
    android:id="@+id/row_one" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Row One"/> 
    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
    </LinearLayout> 
    <LinearLayout 
    android:id="@+id/row_two" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Row Two"/> 
    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
    </LinearLayout> 
    <LinearLayout 
    android:id="@+id/row_three" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Row Three"/> 
    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
    </LinearLayout> 
</LinearLayout> 

请注意所有按钮的ID值是否相同。为了获得对这些按钮的引用,我不能只从我的Activity中调用findViewById() ...我会得到哪一个?然而,findViewById()可以从任何视图被调用,所以我可以做以下获得引用每个按钮:

setContentView(R.layout.main); 

Button one = (Button)findViewById(R.id.row_one).findViewById(R.id.button); 
Button two = (Button)findViewById(R.id.row_two).findViewById(R.id.button); 
Button three = (Button)findViewById(R.id.row_three).findViewById(R.id.button); 

现在我不得不每一个独特的按钮的引用,即使他们有相同的ID。话虽如此,如果您的应用程序与示例匹配,我仍然不主张这样做。创建唯一的ID引用有助于保持代码的可读性。

HTH!

+0

谢谢Devunwired,我确实调用findViewById()每个视图vs活动。我手动管理我的视图并在它们之间进行自定义转换,所以在启动时我膨胀并绑定按钮。这就是为什么Android如此令人困惑,为什么Android不尊重ID,因为这是我的计划的一个关键部分(我不想为整个项目命名每个按钮)。 – watcher278