【问题标题】:How to interface from Parent Activity to child fragments?如何从父活动接口到子片段?
【发布时间】:2013-11-07 17:27:18
【问题描述】:

我正在使用ActionBar 创建一个Activity 和一个ViewPager 和3 个Fragments。当我的父 Activity 首次创建时,我调用一个 Web 服务并尝试将结果返回到三个单独片段的 UI。到目前为止,我已经尝试向父活动添加一个接口并在子片段中实现它,但我得到一个空指针异常。我的代码如下:

在父活动中我声明一个接口

public interface CommunicateResultsToChilden{
    public void displayResultInfo(JSONObject response);

}

在 HttpGet 返回后我调用:

communicateResults.displayResultInfo(response);

然后在子片段中我说

public class ChildFrag1 extends Fragment implements CommunicateResultsToChildren{



 @Override public void onCreate(Bundle savedIstanceState){
                // initialize objects
  }

 public void displayResultInfo(JSONObject response){
       // It never makes it to this call inside the method
       Log.d("RESPONSE", "JSONObject : " + response);
 }

}

在我打电话给communicateResults.displayResultInfo(response);之前

如何获取我刚刚创建的这个接口的引用?

解决方案

我在

中添加了 thi
protected class CustomViewPagerAdapter extends FragmentStatePagerAdapter {

   // ....// Methods from tutorial on android developer swipe tabs

   public Fragment getItem(int Position){
                // Each time the view pager calls getItem(position)
                // this is called
                instantiatedFragment(fragment);

    }

}

在我的主班

 public instantiatedFragment(Fragment fragment){
       if(fragment != null){
               try{
                    // Member Variable instance of CommunicateResultsToChildren
                    newInterface = (CommunicateResultsToChildren) fragment;
                    mInterfaceList.add(newInterface);
                 }catch(Exception ex){
                     // Pop up dialog with exception message
                     // telling user
                 }
       }
 }

【问题讨论】:

  • 有人可以帮我吗?这是世界上最令人沮丧的事情……现在。每次我得到空指针异常!!!!

标签: android interface android-fragments


【解决方案1】:

根据ViewPager的当前位置获取Fragment对象,然后简单地调用childFrag1.displayResultInfo(response);并将JSONObject response传入其中。

【讨论】:

  • hmmm 是的,我已经看到了一个有效的示例,但是将它移植到我的代码中有点困难。我需要为每个片段添加接口,如果片段在视图中,否则我也会得到一个空指针。
  • 你已经在 Fragments 中实现了接口,不是吗?
  • 我是,但如果你愿意的话,没有建立到片段的链接。换句话说,当我在我的活动中创建片段时,我需要将此接口添加到片段中。我该怎么做?
  • 只是一个旁注,当我完成后我会越来越近,我会发布我的解决方案!
【解决方案2】:

你有两种方法可以做到这一点:

  • 对活动使用事件回调 => LINK
  • 最好的方法是使用事件总线框架,例如来自 square 的 Otto

【讨论】:

    【解决方案3】:

    好的,所以我设法在这里使用http://developer.android.com/training/implementing-navigation/lateral.html 回答我自己的问题,然后在我的CustomViewPager 内部类中添加一个方法,每次我将fragment 添加到@987654325 时都会添加上面提到的interface @。然后在主类中我保留一个ArrayList<MainActivity.CommunicateResultsToChildren>(),它包含每个子片段的所有接口。我在communicateResults 类中创建了一个成员,该成员在我的回调方法中使用,从HTTPGet 请求调用communicateResults.displayResultsInfo(response)

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 2014-04-04
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      相关资源
      最近更新 更多