如何拦截片段中的后退按钮?

时间:2013-05-12 12:38:00

标签: android android-viewpager fragment back-button android-fragmentactivity

我是Android编程的新手,我需要帮助:我需要拦截片段中的后退按钮以显示退出警报对话框。我用onBackPressed和onKeyDown都尝试了,但它们不起作用,我不知道为什么...... 这里有一些代码:

public class Home extends Fragment {
    private Dialog dialog;
   // onAttach : set activity listener
   @Override
   public void onAttach(Activity activity) {
      super.onAttach(activity);
      // if implemented by activity, set listener
      // else create local listener (code never executed in this example)
   }

   // onCreateView : 
   @Override
   public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {

      // fragment not when container null
      if (container == null) {
         return null;
      }
      // inflate view from layout
      final View view = inflater.inflate(R.layout.home,container,false);

        ...

        //onBackPressed(); doesn't work, alertDialog comes up only the first time without touching back button
      return view;
   }

我的“onBackPressed”......

public void onBackPressed() {
            new AlertDialog.Builder(getActivity())
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Hey!")
                .setMessage("Exit?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    FragmentActivity i=getActivity(); 
                    i.finish();
                }

            })
            .setNegativeButton("No", null)
            .show();
        }

    }

如果您需要,还可以在这里找到PagerTabsActivity和PagerAdapter ...... PagerTabsActivity:

public class PagerTabsActivity extends FragmentActivity {
    private static int i=0;
    private static View pagerStrip;
    // list contains fragments to instantiate in the viewpager
    List<Fragment> fragments = new Vector<Fragment>();
    List<String> fragmentTitles = new Vector<String>();
    // page adapter between fragment list and view pager
    private PagerAdapter mPagerAdapter;
    // view pager
    private ViewPager mViewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // creating fragments and adding to list
        fragments.add(Fragment.instantiate(this, Home.class.getName()));
        fragmentTitles.add(Home.class.getSimpleName());
        fragments.add(Fragment.instantiate(this, Second.class.getName()));
        fragmentTitles.add(Second.class.getSimpleName());
        fragments.add(Fragment.instantiate(this, Third.class.getName()));
        fragmentTitles.add(Third.class.getSimpleName());
        //
        mViewPager = (ViewPager) findViewById(R.id.pager);
        pagerStrip = findViewById(R.id.pagerTabStrip);
        if (pagerStrip instanceof PagerTabStrip) {
            PagerTabStrip pagerTabStrip = (PagerTabStrip) pagerStrip;
            pagerTabStrip.setDrawFullUnderline(true);
            pagerTabStrip.setTabIndicatorColorResource(android.R.color.white);
            // pagerTabStrip.setTextColor(color.white);
        } else if (pagerStrip instanceof PagerTitleStrip) {
            PagerTitleStrip pagerTitleStrip = (PagerTitleStrip) pagerStrip;
            pagerTitleStrip.setTextColor(getResources().getColor(android.R.color.white));
        }

        this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
        mViewPager.setAdapter(this.mPagerAdapter);
        mViewPager.setCurrentItem(0);
    }
}

PagerAdapter:

public class PagerAdapter extends FragmentPagerAdapter {
    // private String titles[] = new String[] { "Tab1", "Tab2", "Tab3" };
    private List<String> fragmentTitles;
    private List<Fragment> fragments;

    public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public CharSequence getPageTitle(int position) {

        if (null == fragmentTitles || fragmentTitles.size() <= position) {
            return " ";
        }
        String fragTitle = fragmentTitles.get(position);
        if (null == fragTitle || fragTitle.trim().length() == 0) {
            return "No Title";
        }
        // Log.v("TitleAdapter - getPageTitle=", fragmentTitles.get(position));
        return fragmentTitles.get(position);
    }

    @Override
    public Fragment getItem(int position) {
        // Log.v("TitleAdapter - getItem=", String.valueOf(position));
        return this.fragments.get(position);
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }

}

任何帮助将不胜感激! :)

1 个答案:

答案 0 :(得分:0)

您需要覆盖该方法..尝试此代码:

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Exit")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton("No", null)
        .setPositiveButton("Get me out!", new OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                FragmentActivity i=getActivity(); 
                i.finish();
            }
        }).create().show();
}