无法检测到按下后退按钮

时间:2017-06-08 13:34:48

标签: android android-layout android-fragments android-viewpager onbackpressed

我的viewpager里面有几个片段。当用户按下按钮时我需要确认。但是,除非我访问最后一页,否则它不会被调用。

public class Create_Safety_CheckList_MainFragment extends Fragment
        implements View.OnClickListener, Observer {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_create_safety_checklist_pager_main, container, false);
        initializeUI();

        return view;
    }

    private void initializeUI() {
        setHeader(getResources().getString(R.string.safety_check_list_checklist_screen_name));
        addFragments();
        mPager = (ViewPager) view.findViewById(R.id.viewPager_home_screen_activity);
        mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
        mPager.setOffscreenPageLimit(fragmentArrayList.size());
        mPager.setOnPageChangeListener(onPageChangeListener);
        mPager.setAdapter(mPagerAdapter);
//        mPager.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                v.getParent().requestDisallowInterceptTouchEvent(true);
//                return false;
//            }
//        });


        customTextViewChecklistName = (CustomTextView) view.findViewById(R.id.textView_New_Checklist_Name);
        if (createChecklistObservationModel.getChecklistName() != null)
            customTextViewChecklistName.setText(createChecklistObservationModel.getChecklistName());

    }

    private void addFragments() {
        createChecklistAdditionalTabFragment = new CreateChecklistAdditionalTabFragment();
        fragmentArrayList.add(createChecklistAdditionalTabFragment);

        Bundle bundle = getArguments();
        if (bundle != null) {
            if (bundle.containsKey("***")) {
                String response = spcl_databaseHandler.getSpecificChecklistAdditionals(bundle.getString("checklistID"));
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject dataJsonObject = jsonObject.getJSONObject("Data");

                    JSONArray checkListAdditionalFieldDtoJsonArray = dataJsonObject.getJSONArray("***");
                    int additionalsLength = checkListAdditionalFieldDtoJsonArray.length();
                    if (additionalsLength > 0) {
dataJsonObject.getJSONArray("***").toString());
                        additionalInfoFragment = new Additional_Information_Fragment();
                        fragmentArrayList.add(additionalInfoFragment);
                    }

                    JSONArray jsonGroupsArray = dataJsonObject.getJSONArray("***");
                    int groupsLength = jsonGroupsArray.length();
                    for (int i = 0; i < groupsLength; i++) {
                        JSONObject groupJsonObject = (JSONObject) jsonGroupsArray.get(i);
                        JSONArray questionsJsonArray = groupJsonObject.getJSONArray("Questions");
                        int questionsLength = questionsJsonArray.length();
                        for (int j = 0; j < questionsLength; j++) {
                            checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();
                            checklistGroupsDiscussionQuestionOneFragment.setArguments(bundle1);
                            fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                        }

                        JSONArray subGroupsJsonArray = groupJsonObject.getJSONArray("SubGroups");
                        int subGroupsJsonArrayLength = subGroupsJsonArray.length();
                        for (int j = 0; j < subGroupsJsonArrayLength; j++) {
                            JSONObject subGroupObject = subGroupsJsonArray.getJSONObject(j);
                            JSONArray subGroupQuestionsJsonArray = subGroupObject.getJSONArray("Questions");
                            int subGroupQuestionsJsonArrayLength = subGroupQuestionsJsonArray.length();
                            for (int k = 0; k < subGroupQuestionsJsonArrayLength; k++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();                                fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        questionsFragment = new Other_Questions_Fragment();
        membersFragment = new Inspection_Members_Fragment();

        fragmentArrayList.add(questionsFragment);
        fragmentArrayList.add(membersFragment);
    }

    private void setHeader(String headerTitle) {
    }

    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int pageNumber) {
        }

        @Override
        public void onPageScrolled(int pageNumber, float positionOffset,
                                   int positionOffsetPixels) {
//            mPager.getParent().requestDisallowInterceptTouchEvent(true);
            showArrows(pageNumber);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_Next:
                break;

            case R.id.imageView_Previous:
                break;

            case R.id.textView_Cancel :
                callToCloseDialog();
                break;

            default:
                break;
        }
    }

    private void callToCloseDialog() {
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.cancel_dialog_message))
                .setTitle("Warning");

        builder.setPositiveButton(getResources().getString(R.string.cancel_dialog_yes_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                getActivity().getSupportFragmentManager().popBackStackImmediate(getResources().getString(R.string.new_checklist_fragment), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        });

        builder.setNegativeButton(getResources().getString(R.string.cancel_dialog_no_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked cancel button
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void update(Observable observable, Object o) {
    }

    /**
     * A simple pager adapter that represents 3 objects, in sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentArrayList.get(position);
        }

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

    private void showArrows(int pageNumber) {
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                callToCloseDialog();
                return true;
            }
        });
    }

    @Override
    public void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Subscribe
    public void onEvent(QuestionResponsesModel questionResponsesModel){
    }

}

仅保留Viewpager&amp;的代码。片段加载。

2 个答案:

答案 0 :(得分:1)

默认情况下Fragment没有任何反向按下事件,因此您必须使用以下代码通过Activity onBackPressed()方法进行管理。

在您的“活动”中覆盖onBackPressed()方法并对其进行“应用检查”。

 @Override
    public void onBackPressed() {
      // put condition here
        if("Your Fragment is Visible"){
           //Apply confirmation check here 
        }
        else{
            super.onBackPressed();
        }

    }

答案 1 :(得分:0)

您可以在活动中覆盖此方法并收听backpress

public class MainActivity extends Activity {
        ...
        @Override
        public boolean dispatchKeyEvent(KeyEvent event) 
        {
            int action = event.getAction();
            int keyCode = event.getKeyCode();
            switch (keyCode) 
            {
                case KeyEvent.KEYCODE_BACK:
                    if (action == KeyEvent.ACTION_DOWN)
                    {
                        Log.v("myApp", "Back button pressed.");
                        return true;
                    }
                default:
                    return false;
            }
            return false;
        }
    }