通常,对同一视图具有多个视图不是一个好主意
id。这就是造成混乱的原因。
注意:以下是OP使用的适合其特定需求的解决方案:
一种简单的解决方案是使用
onClickXML文件中的属性。您可以将相同的onClick方法分配给多个项目。像这样:
并在您的activity.java中添加以下内容:
public void buttonClicked(View v){ Log.d("TAG","Button clicked!!" // do stuff here}第二个选择 :
当您使用的设置一个按钮的侦听器
id时
button_1,不会同时设置
listener两个按钮的监听器,而只会为第一个按钮设置监听器。如果要
listener为两者都设置相同的值,则要做的就是将这些按钮分配不同
ids,然后将它们分配相同
listener。
这是您应该做的:
Listener myListener = new Listener(){.. blah blah....};((Button) findViewById(R.id.some_id)).setListerner(myListener);((Button) findViewById(R.id.some_other_id)).setListerner(myListener);第三种选择 :
findViewById(R.id.id_of_layout1).findViewById(R.id.button_1)findViewById(R.id.id_of_layout2).findViewById(R.id.button_1)
在这种情况下,您需要向布局文件中添加一些ID,例如:layout_1.xml:
<RelativeLayout android:id="+id/id_of_layout1" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/button_1" android:text="button2" android:background="@android:color/black" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>



