按下背面,有时转到上一个片段,有时退出

时间:2019-03-17 19:40:48

标签: java android android-fragments kotlin onbackpressed

我有一个问题。 我正在制作一个应用程序,其中一个Activity上有几个片段。 App's home fragment 我正在使用具有三个元素的底部导航。 在其中一个元素中,我已从一个片段转移到另一个片段。 from HomeFragment to MagnetListFragment 当我从该片段转到BasketFragment(底部导航的第三元素)并按返回按钮时,它将使我返回到上一个片段MagnetListFragment,而不是退出应用程序。

如果我直接从主页片段转到BasketFragmentProfileFragment,则后退按钮会正常工作。从应用程序退出。

我试图为覆盖onBackPress方法创建新的类和接口,但是它不起作用。 我将popbackstack方法放入MagnetListFragment中,但是它也不起作用。在那之后,它甚至没有进入那个班级。

这是我的MainActivity

    public class MainActivity extends AppCompatActivity implements MagnetListFragment.OnListFragmentInteractionListener {

    private Toolbar toolbar;

    // index to identify current nav menu item
    public static int navItemIndex = 0;

    // Tags to attach fragments
    private static final String TAG_HOME = "home";

    private static final String TAG_HOME_FRAGMENT = "home_fragment";
    public static String CURRENT_TAG = TAG_HOME;
    private static final String TAG_FRAGMENT_OTHER = "other_fragment";

    private Handler mHandler;

    public static BottomNavigationView bottomNavigationView;
    CoordinatorLayout coordinatorLayout;
    Fragment fragment;

    @Override
    public void onListFragmentInteraction(MagnetItem item) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = findViewById (R.id.toolbar);
        setSupportActionBar(toolbar);
        mHandler = new Handler();
        setUpNavigationView();
        coordinatorLayout = findViewById(R.id.coordinator_layout);

        bottomNavigationView = findViewById(R.id.bottom_navigation);

        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bottomNavigationView.getLayoutParams();
        layoutParams.setBehavior(new BottomNavigationBehaviour());

        bottomNavigationView.setSelectedItemId(R.id.navigation_home);
        fragment = new HomeFragment();
        loadFragment(fragment);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                switch (menuItem.getItemId()) {
                    case R.id.navigation_home:
                    fragment = new HomeFragment();
                    break;
                    case  R.id.navigation_proflie:
                        fragment = new ProfileFragment();
                        break;
                    case R.id.navigation_basket:
                        fragment = new BasketFragment();
                        break;
                        default:
                            fragment = new HomeFragment();
                }
                return loadFragment(fragment);
            }
        });

        if (savedInstanceState == null) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
        }

    }

    public void setUpNavigationView() {
        //Setting Navigation View Item Selected Listener to handle the item click of the bottom_navigation menu

        getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0 ) {
              //      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            onBackPressed();
                        }
                    });
                } else  {
                    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

                    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    });
                }
            }
        });
    }
    /***
     * Returns respected fragment that user
     * selected from bottom_navigation menu
     */
    private void loadHomeFragment() {

        Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                // this updates image by replacing fragments
         //       Fragment fragment = getHomeFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                        .beginTransaction();
                fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
          //      fragmentTransaction.replace(R.id.fragment_container, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };
        // If mPendingRunnable is not null, then add to the message queue
        if (mPendingRunnable != null) {
            mHandler.post(mPendingRunnable);
        }
        invalidateOptionsMenu();
    }

/*    private void setToolbarTitle() {
        getSupportActionBar().setTitle(activityTitles[navItemIndex]);
    }*/

            @Override
    public boolean onCreateOptionsMenu(Menu menu) {

                return true;
            }

            @Override
    public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();
                //noinspection SimplifiableIfStatement

                return super.onOptionsItemSelected(item);
            }

    private boolean loadFragment(Fragment fragment) {
        //switching fragment
        if (fragment != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, fragment)
                    .commit();
            return true;
        }
        return false;
    }
}

这是我的HomeFragment

    public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private static final String TAG = "RecyclerViewFragment";
    private static final String LAYOUT_MANAGER = "layoutManager";

    private static final String TAG_MAGNET_LIST_FRAGMENT = "magnet_list";
    private static final String TAG_CALENDAR = "calendar";

    private static final String TAG_PROFILE = "profile";

    protected RecyclerView mRecyclerView;
    protected PrintingAdapter mPrintingAdapter;
    protected RecyclerView.LayoutManager mLayoutManager;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private Callback<List<Printing>> callback;

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public interface ClickListener {
        void onClick(View view, int position);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        rootView.setTag(TAG);
        mRecyclerView = rootView.findViewById(R.id.recycler_view);
        mLayoutManager = new LinearLayoutManager(this.getContext());
        mPrintingAdapter = new PrintingAdapter();
        mRecyclerView.setAdapter(mPrintingAdapter);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        mRecyclerView.setLayoutManager(mLayoutManager);

        mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity().getApplicationContext(), mRecyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                Toast.makeText(getActivity().getApplicationContext(), "You just tapped # " + position, Toast.LENGTH_SHORT).show();
                switch (position) {
                    case 0:
                        Fragment magnetListFragment = new MagnetListFragment();
                        FragmentTransaction transaction = getFragmentManager().beginTransaction();
                        transaction.replace(R.id.fragment_container, magnetListFragment);
                        transaction.addToBackStack(TAG_MAGNET_LIST_FRAGMENT);
                        transaction.commit();
                        break;
                    case 1:
                        Fragment calendarFragment = new CalendarFragment();
                        FragmentTransaction transactionCalendar = getFragmentManager().beginTransaction();
                        transactionCalendar.replace(R.id.fragment_container, calendarFragment);
                        transactionCalendar.addToBackStack(TAG_CALENDAR);
                        transactionCalendar.commit();
                        break;
                }
            }
        }));

      //  ArrayList<Printing> printings = new ArrayList<>();
        for (int i = 0; i< Data.names.length; i++) {
            Printing printing = new Printing(Data.names[i], Data.photosOfMainList[i]);
            mPrintingAdapter.addPrinting(printing);
        }

        return rootView;

    }

    @Override
    public void onResume() {
        super.onResume();
        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.app_name);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
/*        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

那是BasketFragment

class BasketFragment : Fragment(), IOnBackPressed {

companion object {
    fun newInstance() : BasketFragment {
        return BasketFragment()
    }
}

private val TAG_BASKET_FRAGMENT = "basket"

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    onBackPressed()

    return inflater?.inflate(R.layout.fragment_basket, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val button = activity?.findViewById(R.id.chayra_button) as Button
    button.setOnClickListener {
        val homeFragment = HomeFragment()
        val fragmentManager = activity!!.getSupportFragmentManager()
        val transaction = fragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, homeFragment)
        fragmentManager.popBackStack(null, POP_BACK_STACK_INCLUSIVE)
     //   transaction.addToBackStack(TAG_BASKET_FRAGMENT)
        transaction.commit()
        bottomNavigationView.setSelectedItemId(R.id.navigation_home)
    }
    super.onViewCreated(view, savedInstanceState)
}

override fun onResume() {
    (activity as AppCompatActivity).supportActionBar!!.setTitle(R.string.app_name)
    (activity as AppCompatActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(false)
    super.onResume()
}

override fun onBackPressed(): Boolean{
 return true
}

}

那就是ProfileFragment

class ProfileFragment : Fragment() {

companion object {
    fun newInstance() : ProfileFragment {
        return ProfileFragment()
    }
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater?.inflate(R.layout.fragment_profile, container, false)
}

override fun onResume() {
    (activity as AppCompatActivity).supportActionBar!!.setTitle(R.string.app_name)
    (activity as AppCompatActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(false)
    super.onResume()
}

}

它是重写BackPressed类,但我认为它已经过时了。

open class BackPressed : AppCompatActivity() {
override fun onBackPressed() {
    val homeFragment = HomeFragment()
    val fragmentManager = getSupportFragmentManager()
    val transaction = fragmentManager.beginTransaction()
    transaction.replace(R.id.fragment_container, homeFragment)
    fragmentManager.popBackStack("BackPressedClass", FragmentManager.POP_BACK_STACK_INCLUSIVE)
    //   transaction.addToBackStack(TAG_BASKET_FRAGMENT)
    transaction.commit()
    MainActivity.bottomNavigationView.setSelectedItemId(R.id.navigation_home)
   super.onBackPressed()
}

   // override fun onBackPressed() {
/*        val fragment =
                this.supportFragmentManager.findFragmentById(R.id.fragment_container)
        (fragment as? IOnBackPressed)?.onBackPressed()?.not()?.let {
            val fragmentManager = supportFragmentManager
            fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
            super.onBackPressed()
        }*/
    }

及其接口

    interface IOnBackPressed{
    fun onBackPressed(): Boolean
}

0 个答案:

没有答案