是否可以在同一布局中有2个具有相同功能的按钮?

时间:2013-03-19 16:06:36

标签: android

我有一个包含搜索选项的长列表。我想在列表的顶部和底部有一个按钮来“搜索”。两个按钮都具有相同的功能。我认为可以在最后复制并通过xml布局中的第一个按钮,但最后的按钮没有任何功能。如何在我的Activity中添加一堆额外的代码来实现这一点?

<ScrollView 
    android:layout_width= "fill_parent"
    android:layout_height= "fill_parent" >

<LinearLayout
    android:id="@+id/LinearLayout02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

<Button android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/save_search_options"
    android:text="Search" android:textSize="25dip"></Button>

<!--search options in between-->


<Button android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/save_search_options"
    android:text="Search" android:textSize="25dip"></Button>

</LinearLayout>
</ScrollView>

4 个答案:

答案 0 :(得分:2)

您只需添加

即可
Button
 ...
 android:onClick="functionName"

两个按钮然后在Activity中创建一个功能

public void functionName(View v)
{
     //some logic
}
然后它会知道你按了哪个。但是,将Button放在List

之上可能会更有效率

答案 1 :(得分:1)

如果您将相同的onClickListener附加到每个android:onClick,则它们将具有相同的功能。您可以使用XML {{1}} XML属性在XML中执行此操作以避免代码。

答案 2 :(得分:0)

您有两个ID相同的按钮。重命名其中一个并将侦听器分配给它们。

答案 3 :(得分:0)

为2按钮设置不同的ID,所以代码将是这样的

<ScrollView 
    android:layout_width= "fill_parent"
    android:layout_height= "fill_parent" >

<LinearLayout
    android:id="@+id/LinearLayout02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

<Button android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/top_save_search_options"
    android:text="Search" android:textSize="25dip"></Button>

<!--search options in between-->


<Button android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/bottom_save_search_options"
    android:text="Search" android:textSize="25dip"></Button>

</LinearLayout>
</ScrollView>

并使用您设置的不同ID声明活动中的按钮,并且可以将同一个侦听器设置为两个按钮

相关问题