【问题标题】:Android - Communicating from Activity to fragment that it hostsAndroid - 从 Activity 与其托管的片段进行通信
【发布时间】:2013-08-26 10:23:21
【问题描述】:

目前我一直潜入Fragment世界:http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

我知道通过在片段中创建一个侦听器然后在承载片段的 Activity 中实现它是从片段到 Activity 进行通信的好方法,但是我如何从 Activity 与片段进行通信?另一个听众?也许我不完全理解听众在做什么。非常感谢有关此主题的任何帮助,解释如何从活动到片段进行通信!

附:我目前正在将我制作的活动(B)转换为片段。在开始 Activity B 之前,我曾经从 Activity A 做一些 intent.putExtra("value") 所以这就是我想要替换的东西......可能对你没有帮助,但我想我会试着把它透视我在做什么。

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    我可能已经找到了解决方案,哈哈。我会做一些检查以确保它有效并稍后确认。

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    
            Bundle b = getActivity().getIntent().getExtras();
            wid = b.getString("wid");
            rid = b.getString("rid");
            View view = inflater.inflate(R.layout.categoryfragment, container, false);
    return view;
    }
    

    【讨论】:

      【解决方案2】:

      就像创建 Activity 时一样,您可以将 Bundle 传递给 Fragment

      Fragment class reference 上有一个关于如何做到这一点的示例。

      /**
       * Create a new instance of DetailsFragment, initialized to
       * show the text at 'index'.
       */
      public static DetailsFragment newInstance(int index) {
          DetailsFragment f = new DetailsFragment();
      
          // Supply index input as an argument.
          Bundle args = new Bundle();
          args.putInt("index", index);
          f.setArguments(args);
      
          return f;
      }
      

      使用getArguments() 找回Bundle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多