【问题标题】:Android: Communication between Activity and Fragment ActivityAndroid:Activity和Fragment Activity之间的通信
【发布时间】:2014-07-17 17:03:58
【问题描述】:

我有一个正常的 android 活动,其中包含选项列表视图。选择选择时,它通过意图启动片段活动。这个片段活动本身包含一个操作栏,由 3 个片段组成。

我想要做的是基于对活动的选择(其中包含 选择)是将选定的位置编号发送到片段活动,从而发送3个片段

我发现了有关接口的信息,但这些示例令人难以理解,有人可以在这里帮助我吗?我只想将选定的位置发送到其他片段。

【问题讨论】:

    标签: java android android-fragments interface


    【解决方案1】:

    通过Bundle可以将选中的位置从Activity传递给FragmentActivity

    您的 Intent 应如下所示:

    Intent intent = new Intent(Activity.this, FragmentActivity.class);
    intent.putExtra("idforthevalue",selectedPOsition);
    startActivity(intent);
    

    然后您可以在 FragmentActivity 上检索该值:

    Bundle extras = getIntent().getExtras();
        int position = 0;
        if(extras != null) {
            position = extras.getInt("idforthevalue");
        }
    

    根据您添加片段的方式,您还可以使用 FragmentTransaction 中的 FragmentActivity 中的 Bundle 将此值传递给它们

    FragmentManager fragmentManager = getFragmentManager();  // or getSupportFragmentManager() if you are using compat lib
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
    FragmentX fragmentX = new FragmentX();
    Bundle bundle = new Bundle();
    bundle.putInt("idforthevalue", position);
    fragmentX.setArguments(bundle);
    
    fragmentTransaction.replace(id_of_container, fragmentX).commit();
    

    你可以再次检索片段中的值

            Bundle bundle = getArguments();
            if(bundle != null) {
                position = bundle.getInt("idforthevalue", 0);
            }
    

    您可以对三个 Fragment 执行相同的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多