如何使用XML的onClick片段内,以处理按钮点击 [英] How to handle button clicks using the XML onClick within Fragments
问题描述
pre-蜂巢(Android的  3),每个活动获得登记,通过在布局的XML中的的onClick
标签来处理按钮点击:
Pre-Honeycomb (Android 3), each Activity was registered to handle button clicks via the onClick
tag in a Layout's XML:
android:onClick="myClickMethod"
之内,你可以使用这个方法 view.getId()
和switch语句做的按钮逻辑。
Within that method you can use view.getId()
and a switch statement to do the button logic.
通过引进蜂窝我打破这些活动成了碎片,可里面的许多不同的活动中重复使用。大部分按钮的行为是活动独立的,我想code驻留在片段内文件的没有的使用注册<$旧(pre 1.6)的方法C C> OnClickListener $每个按钮。
With the introduction of Honeycomb I'm breaking these Activities into Fragments which can be reused inside many different Activities. Most of the behavior of the buttons is Activity independent, and I would like the code to reside inside the Fragments file without using the old (pre 1.6) method of registering the OnClickListener
for each button.
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
现在的问题是,当我布置的充气它仍然是托管的活动正在接收按钮点击,而不是单独的片段。有没有好的方法为
The problem is that when my layout's are inflated it is still the hosting Activity that is receiving the button clicks, not the individual Fragments. Is there a good approach to either
- 注册片段接收按钮的点击?
- 从传递活动的点击事件,他们属于哪一种?片段
推荐答案
您可能只是做到这一点:
You could just do this:
活动:
Fragment someFragment;
...onCreate etc instantiating your fragments
public void myClickMethod(View v) {
someFragment.myClickMethod(v);
}
片段:
public void myClickMethod(View v) {
switch(v.getId()) {
// Just like you were doing
}
}
在回应@Ameen谁想要更少的耦合,片段重复使用
In response to @Ameen who wanted less coupling so Fragments are reuseable
接口:
public interface XmlClickable {
void myClickMethod(View v);
}
活动:
XmlClickable someFragment;
...onCreate, etc. instantiating your fragments casting to your interface.
public void myClickMethod(View v) {
someFragment.myClickMethod(v);
}
片段:
public class SomeFragment implements XmlClickable {
...onCreateView, etc.
@Override
public void myClickMethod(View v) {
switch(v.getId()){
// Just like you were doing
}
}
这篇关于如何使用XML的onClick片段内,以处理按钮点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!