从活动B打开活动A的特定片段

时间:2013-01-17 08:44:33

标签: java android-intent android-fragments android-activity

再来一次!

情况就是这样,我有:

活动A实现viewPager并可视化3个可能的片段。要访问每个片段,我使用以下代码:

    @Override
    public Fragment getItem(int page) {
        switch (page) {
            case 0: return new MyFirstFragment();
            case 1: return new MySecondFragment();
            case 2: return new MyThirdFragment();
        }
        return null;
    }

    @Override
    public int getCount() {
        return [the count of total fragments];
    }

片段3包含用户列表。当我点击用户时,活动B就启动了。使用意图:

// Create new Intent Object, and specify class
Intent intent = new Intent();
intent.setClass(Fragment3.this, ActivityB.class);
//Use startActivity to start Activity B
startActivity(intent);

在活动B中有一个按钮可以将我重定向到片段2.所以问题是:我怎么能返回看到片段2?我想再次启动活动A并使用putExtra指定应该可视化的片段。

例如,我会在这种情况下传递一个数字2,并且想要调用函数Fragment getItem(2)来可视化片段。但是,Fragment getItem包含在pageadapter类中,所以我不清楚如何继续。

1 个答案:

答案 0 :(得分:15)

最后我自己找到了解决方案:)

我使用了intent.putExtra()来传递我想要显示的片段的位置,然后在被调用的活动中,我使用了ViewPager的方法setCurrentItem(position),并显示了想要的片段。

希望这可以帮助那些遇到同样问题的人!