Android - 使用未从 Activity 调用的 Intent 清除堆栈

Android - Clearing backstack with an Intent NOT called from an Activity

我正在尝试实现一个类似于许多应用程序用作介绍的小型幻灯片,例如 Google Docs。

我将适配器与 activity 分开,以保持一切整洁:

public class IntroActivity extends FragmentActivity {

    private int[] mResources = {
            R.drawable.slide1,
            R.drawable.slide2,
            R.drawable.slide3,
            R.drawable.slide4
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intro);

        CustomPagerAdapter customPagerAdapter = new CustomPagerAdapter(this, mResources);

        ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setAdapter(customPagerAdapter);
    }

}

我的 CustomPagerAdapter 中的以下代码处理最后一张幻灯片上的按钮的单击事件,该按钮通过意图打开 MainActivity。相当标准的东西:

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        if (position == (mResources.length - 1)) {
            System.out.println("POSITION " + position);

            View itemView = mLayoutInflater.inflate(R.layout.pager_last_item, container, false);

            ImageView imageView = (ImageView) itemView.findViewById(R.id.lastImageView);
            imageView.setImageResource(mResources[position]);

            Button btn = (Button) itemView.findViewById(R.id.btn_open_main_activity);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    mContext.startActivity(intent);
                    //TODO destroy IntroActivity.java
                }
            });

            container.addView(itemView);

            return itemView;
          }
         (...) //if not the last slide...

   }

但它似乎不起作用,即使使用那些 Intent 标志也是如此。我无法从 IntroActivity 访问 finish() 方法。 该应用程序运行良好,但当我按下 MainActivity 中的后退按钮时,它会将我带回到最后一张幻灯片。 有办法解决吗?

编辑 - 这就是我创建 PagerAdapter 的方式。我只是从 IntroActivity:

传递上下文和资源数组
public class CustomPagerAdapter extends PagerAdapter {

    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private int[] mResources;

    public CustomPagerAdapter(Context context, int[] mResources) {
        this.mContext = context;
        this.mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.mResources = mResources;
    }

您可以在清单中的 IntroActivity 声明中添加 android:noHistory="true" 属性。

参考this

或者您可以通过构造函数将 activity 引用传递给片段或适配器 claa 并调用 activity.finish()

类似于 new Adapter(mActivity) 并调用 mActivity.finish()