如何在 Fragments 中使用 XML onClick 处理按钮点击 [英] How to handle button clicks using the XML onClick within Fragments

查看:48
本文介绍了如何在 Fragments 中使用 XML onClick 处理按钮点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Pre-Honeycomb (Android 3),每个 Activity 都通过布局的 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.

随着 Honeycomb 的引入,我将这些活动分解成可以在许多不同活动中重复使用的片段.按钮的大部分行为都是独立于活动的,我希望代码驻留在 Fragments 文件中,没有使用注册 OnClickListener 的旧(1.6 之前)方法每个按钮.

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
    }
});

问题是,当我的布局膨胀时,它仍然是接收按钮点击的宿主 Activity,而不是单个 Fragment.有没有好的方法

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

  • 注册片段以接收按钮点击?
  • 将来自 Activity 的点击事件传递给它们所属的片段?

推荐答案

你可以这样做:

活动:

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 希望减少耦合以便 Fragment 可重用


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
    }
}    

这篇关于如何在 Fragments 中使用 XML onClick 处理按钮点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆