如何将三个片段的数据发送到单个活动?

时间:2019-06-09 17:10:01

标签: java android interface fragment

我有一个更简单的问题,但是我无法在互联网上找到答案。这是交易:我有三个片段,我需要将每个片段的数据发送到单个活动,然后打开另一个活动。我打算使用一个接口来做到这一点。因此,我需要为每个片段创建三个接口,并在活动时实现它们?我有三个实现为每个活动获取数据?在编写代码之前,我需要这样做。预先感谢。

Demo image

2 个答案:

答案 0 :(得分:2)

首先,让我们创建一个interface

interface MyInterface {
     fun onSomethingDone(someData: Int)  //A sample function, you can customize it your needs.
 }

然后

在您的活动中

覆盖onAttachFragment。永远记住此规则,切勿将片段紧密地结合到活动。因此,您可以做的是检查片段并进行如下相关操作:

class MyActivity : AppCompatActivity() {

    override onAttachFragment(fragment: Fragment) {

           when (fragment) { //A switch statement, checking using instanceOf() in Java.
             is Fragment1 -> fragment.firstFragmentListener = this //Proviving context of your activity to public variable of each fragment.
             is Fragment2 -> fragment.secondFragmentListener = this
             is Fragment3 -> fragment.thirdFragmentListener = this
         }
     }
 }

这将确保您在设置自定义侦听器时不会紧密耦合片段,就像在特定活动的上下文中投射片段一样。

让我们走向碎片

 class Fragment1 : Fragment() {

     var firstFragmentListener: MyInterface? =  null  //public member, we are accessing it in our activity method, look above! 

      override onCreate() {

          myButton.setOnClickListener {
              firstFragmentListener.onSomethingDone(999) // Just sending random integer as the method parameter.
           }
       }
  }

这个示例片段类应该给您足够的思路来进行设置。就像实现该片段类的方式一样,您可以与Fragment2和Fragment3相同。

回到我们的活动

但是这次,我们将实现一个侦听器方法。

class MyActivity : AppCompatActivity(), MyInterface {

   override fun onSomethingDone(someData: Int) {
      when (someData) {
         999 -> //Came from first fragment
         1000 -> //Second fragment
         1001 -> //Third fragment
      }
    }

    override onAttachFragment(fragment: Fragment) {

           when (fragment) { //A switch statement, checking using instanceOf() in Java.
             is Fragment1 -> firstFragmentListener = this //Proviving context of your activity to public variable of each fragment.
             is Fragment2 -> secondFragmentListener = this
             is Fragment3 -> thirdFragmentListener = this
         }
     }
 }

关于此,我将链接一个链接给您一个疯狂的主意。 Single interface for multiple fragmentsViewModel是第二代Android开发的一部分,不仅提供了片段和活动之间的互通,而且还提供了各种优势。

答案 1 :(得分:1)

您可以通过 New> Java类创建一个单独的接口,然后在对话框中选择种类>接口。 然后,将所需的方法添加到Interface并让Activity实现它。这样做之后,您可以转到Fragments,并在onAttach(Context context)方法中获取该接口的实例,如下所示:

    @Override
    public void onAttach(@NonNull Context context)
    {
        Log.d(TAG, "onAttach:true");

        super.onAttach(context);

        if (context instanceof OnFragmentInteractionListener)
        {
            mFragmentInteractionListener = (OnFragmentInteractionListener) context;
        }
        else
        {
            throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
        }
    }

现在,您可以通过在片段类的任意位置说出mFragmentInteractionListener.deleteInternet(true)来调用Interfaces方法。

如果还有其他问题,请在评论中让我知道。