是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?

因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?


当前回答

非常简短而甜蜜的回答:

getActivity().onBackPressed();

我案例的整个场景说明:

我在MainActivity中有FragmentA, 我从FragmentA打开FragmentB (FragmentB是FragmentA的子或嵌套片段)

 Fragment duedateFrag = new FragmentB();
 FragmentTransaction ft  = getFragmentManager().beginTransaction();
 ft.replace(R.id.container_body, duedateFrag);
 ft.addToBackStack(null);
 ft.commit();

现在如果你想从FragmentB访问FragmentA你可以简单地输入getActivity().onBackPressed();在FragmentB。

其他回答

试试这个,如果你真的想在Fragment中启用onBackPressed()。 在浪费了一个小时的时间后,我根据我以前的经验,做出了这个完全符合需求的解决方案。

你只需要关注私有int STATUS_FRAGMENT=0的值;这就满足了片段中addToBackStack()的需求。

import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.example.growfast.NavigationItemsFolder.CoreFragments.Cart;
import com.example.growfast.NavigationItemsFolder.CoreFragments.HelpDesk;
import com.example.growfast.NavigationItemsFolder.CoreFragments.Home;
import com.example.growfast.NavigationItemsFolder.CoreFragments.ProfileDetails;
import com.example.growfast.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class BusinessManagement extends AppCompatActivity {

    public BottomNavigationView bottomNavigationView;
    private int STATUS_FRAGMENT=0;

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

    }

    private void setBottomNavigationMenu() {
        bottomNavigationView = findViewById(R.id.navigation);
        bottomNavigationView.setVisibility(View.VISIBLE);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

            Fragment fragment = null;

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {

                    case R.id.action_home:
                        fragment = new Home();
                        break;

                    case R.id.action_profile:
                        fragment = new ProfileDetails();
                        break;
                    case R.id.action_cart:
                        fragment = new Cart();
                        break;
                    case R.id.action_favourites_menu:
                        fragment = new HelpDesk();
                        break;

                }
                return loadFromFragment(fragment);

            }
        });
        bottomNavigationView.setSelectedItemId(R.id.action_home);
    }

    private boolean loadFromFragment(Fragment fragment) {
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.my_container, fragment)
                    .commit();
            STATUS_FRAGMENT=1;
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        if (STATUS_FRAGMENT==1) {
            bottomNavigationView.setSelectedItemId(R.id.action_home);
            STATUS_FRAGMENT=0;
            bottomNavigationView.setVisibility(View.VISIBLE);
        }
        else{
            super.onBackPressed();
        }
    }


}```

这一行代码将从任何片段中进行操作,它将弹出backstack上的当前片段。

getActivity().getSupportFragmentManager().popBackStack();

我是这样做的,对我很管用

简单的界面

FragmentOnBackClickInterface.java

public interface FragmentOnBackClickInterface {
    void onClick();
}

示例实现

MyFragment.java

public class MyFragment extends Fragment implements FragmentOnBackClickInterface {

// other stuff

public void onClick() {
       // what you want to call onBackPressed?
}

然后在activity中重写onBackPressed

    @Override
public void onBackPressed() {
    int count = getSupportFragmentManager().getBackStackEntryCount();
    List<Fragment> frags = getSupportFragmentManager().getFragments();
    Fragment lastFrag = getLastNotNull(frags);
    //nothing else in back stack || nothing in back stack is instance of our interface
    if (count == 0 || !(lastFrag instanceof FragmentOnBackClickInterface)) {
        super.onBackPressed();
    } else {
        ((FragmentOnBackClickInterface) lastFrag).onClick();
    }
}

private Fragment getLastNotNull(List<Fragment> list){
    for (int i= list.size()-1;i>=0;i--){
        Fragment frag = list.get(i);
        if (frag != null){
            return frag;
        }
    }
    return null;
}

只需遵循以下步骤:

在添加片段时,

fragmentTransaction.add(R.id.fragment_container, detail_fragment, "Fragment_tag").addToBackStack(null).commit();

然后在主活动中,重写onBackPressed()

if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
    getSupportFragmentManager().popBackStack();
} else {
    finish();
}

要处理应用程序中的后退按钮,

Fragment f = getActivity().getSupportFragmentManager().findFragmentByTag("Fragment_tag");
if (f instanceof FragmentName) {
    if (f != null) 
        getActivity().getSupportFragmentManager().beginTransaction().remove(f).commit()               
}

就是这样!

在kotlin的情况下使用这个onAttach回调

        override fun onAttach(context: Context) {
          super.onAttach(context)
           val callback: OnBackPressedCallback = object : 
                 OnBackPressedCallback(true) {
                 override fun handleOnBackPressed() {
                 // your onbackpressed code 


            }
          }
      requireActivity().onBackPressedDispatcher.addCallback(this, callback)
      }