【问题标题】:Passing data between two fragments在两个片段之间传递数据
【发布时间】:2012-06-24 11:30:29
【问题描述】:

我有两个片段,分别在不同的类中声明 - AFragment 和 BFragment。我的 MainActivity 看起来有点像这样:

public class MainActivity extends SherlockFragmentActivity implements ActionBar.TabListener 
{       
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab firstTab = getSupportActionBar().newTab().setText("Fragment A");           
    ActionBar.Tab secondTab = getSupportActionBar().newTab().setText("Fragment B");

    SherlockFragment firstFragment = new AFragment();
    SherlockFragment secondFragment = new BFragment();

    firstTab.setTabListener(this);
    secondTab.setTabListener(this);

    getSupportActionBar().addTab(firstTab);
    getSupportActionBar().addTab(secondTab);
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
    switch (tab.getPosition())
    {
    case 0:
        ft.replace(R.id.fragment_container, new AFragment());
        break;
    case 1:
        ft.replace(R.id.fragment_container, new BFragment());
        break;
    }
    Toast.makeText(this, tab.getText(), Toast.LENGTH_LONG).show();      
    }
    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }
}

我的问题是,我如何在我的两个片段之间传递一个变量——比如一个整数?例如,我在第一个片段中按下一个按钮,一个特定的整数将出现在第二个片段的 TextView 中。

【问题讨论】:

  • 你应该用[android-actionbar]而不是[actionbar]标记这个:)

标签: android android-fragments actionbarsherlock android-actionbar


【解决方案1】:

片段是为了重复使用...也就是说,两个片段应该直接在彼此之间传递数据。相反,您应该在 Activity 中定义 callback method。这将确保您可以在需要时在应用程序的其他地方(以及您制作的其他应用程序)中重复使用您的片段。

【讨论】:

  • 谢谢!我发现他们给出的例子有点难以理解,虽然:(特别是因为我没有使用 ListFragment。你能给我一个绝对基本的例子,比如按钮吗?对不起,我是个菜鸟。: )
猜你喜欢
  • 2018-04-16
  • 2018-09-25
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多