场景:我在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/