Android default button-listener?
I have 26 Buttons on my activity (alphabet). For all of them I want to have the same onclick-listener. Is there another way to set the "default-o开发者_如何学运维nlick-listener" for all buttons, without set them via button.setOnClickListener(...)
?
Would be great.
Thanks
In your layout, you can specify android:onClick
for each button. Also, since this is just another attribute, you can also specify this in a style or Theme, effectively setting all of them at once.
The drawback to doing this as a theme is that the onClick will be applied to ALL views. Probably not what you want. So, I'd suggest just specifying android:onClick
on each button.
Another approach would be to create a custom view that extends from Button and provides the common onClick functionality there.
Here is an example of using the android:onClick
approach. In your layout, define your buttons and supply the onClick value:
<Button
android:id="@+id/button1"
android:tag="a"
android:onClick="doSomething"
... />
<Button
android:id="@+id/button2"
android:tag="a"
android:onClick="doSomething"
... />
<Button
android:id="@+id/button3"
android:tag="b"
android:onClick="doSomething"
... />
And your activity would have the doSomething
method:
public void doSomething(View v) {
// in here, we can branch off based on the ID or the tag.
switch (v.getId()) {
case R.id.button1:
// something
break;
case R.id.button2:
// something
break;
case R.id.button3:
// something
break;
}
if (v.getTag() != null && v.getTag().equals("a")) {
// do something for the button's tagged with 'a'
}
}
try unsing the android:onClick="myOnClickListener" property within your layout xml.
Example:
<Button
android:text="A"
android:id="@+id/ButtonA"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="MyOnClickListener">
</Button>
精彩评论