android - android布局中按钮的通用监听器?

标签 android

场景:我在xml中定义了三个按钮

<button android:id="@+id/firstbtn" 
    ...
/>
<button android:id="@+id/secbtn" 
    ...
/>
<button android:id="@+id/thirdbtn" 
    ...
/>
In Java one way to  listen to them is  
Button firstbtn = (Button) findViewById(R.id.firstbtn);  
    firstbtn.setOnClickListener(new View.OnClickListener() {  
            public void onClick(View v) {  
                Toast.makeText(getBaseContext(),   
                        "You have clicked first button",   
                        Toast.LENGTH_SHORT).show();  
            }  
        });  

对于第二个 btn ,必须使用不同的 id 重复相同的代码 ??
我怎样才能让它足够通用,它可以监听所有按钮(比如在 for 循环中)并且在处理时我应该能够区分不同的 btns。 (可能是获取元素id)

最佳答案

我更喜欢使用 onClick="methodName" xml 属性,而不是大量的 findViewById 调用。例如:

<LinearLayout ...>
  <Button android:text="1" onClick="onButtonClicked" clickable="true" />
  <Button android:text="2" onClick="onButtonClicked" clickable="true" />
  <Button android:text="3" onClick="onButtonClicked" clickable="true" />
  <Button android:text="4" onClick="onButtonClicked" clickable="true" />
</LinearLayout>

在显示布局的 Activity 中只需添加一个方法

public void onButtonClicked(View v){
     // do whatever needs to be done. For example:
     Toast.makeText(getApplicationContext(), ((Button) v).getText() + " clicked", Toast.LENGTH_SHORT).show(); 
}

您还可以将 onClick 和 clickable 属性放入 res/styles.xml 文件中以节省更多输入:

<?xml version="1.0" encoding="UTF-8" ?>
<resources>
  <style name="clickable_button" >
    <item name="android:onClick" >onButtonClicked</item>
    <item name="android:clickable" >true</item>
  </style>
</resources>

然后您的布局被简化为

<LinearLayout ...>
  <Button android:text="1" style="@style/clickable_button" />
  <Button android:text="2" style="@style/clickable_button" />
  <Button android:text="3" style="@style/clickable_button" />
  <Button android:text="4" style="@style/clickable_button" />
</LinearLayout>

关于android - android布局中按钮的通用监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3913758/

相关文章:

android - 如何授予xamarin相机权限

java - 预定闹钟重复时钟 android 的每一分钟

android - 仅在单元测试期间出现 DateFormat ParseException

Android Studio 2.3.1 按钮在模拟器或实际设备中的位置不正确

android - ListView不可点击,行中的所有小部件都是TextView

android - 不同版本如何在市场上运作?

android - 实现细粒度启用/禁用推送通知

android - 从 SD 卡中获取多个图像以显示在 Coverflow 中

android - 将通过 Intent.ACTION_PICK 选取的图像复制到文件

java - 在另一个 Activity 中显示选定的图像