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

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


当前回答

你应该添加接口到你的项目如下;

public interface OnBackPressed {

     void onBackPressed();
}

然后,你应该在你的片段上实现这个接口;

public class SampleFragment extends Fragment implements OnBackPressed {

    @Override
    public void onBackPressed() {
        //on Back Pressed
    }

}

你可以在你的onBackPressed事件下面触发这个onBackPressed事件,如下所示;

public class MainActivity extends AppCompatActivity {
       @Override
        public void onBackPressed() {
                Fragment currentFragment = getSupportFragmentManager().getFragments().get(getSupportFragmentManager().getBackStackEntryCount() - 1);
                if (currentFragment instanceof OnBackPressed) {  
                    ((OnBackPressed) currentFragment).onBackPressed();
                }
                super.onBackPressed();
        }
}

其他回答

试试这个,如果你真的想在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();
        }
    }


}```

在Fragments中处理onBackPressed()的简单方法

步骤1: 在activity中创建一个静态布尔值。

public static Fragment_one;

步骤2: 在On Create方法中的MainActivity(持有片段的活动)上声明

Fragment_one=true;

步骤3:在MainActivity中覆盖onBackPressed()

@Override
public void onBackPressed() {

    if(Fragment_one) {
     //Back key pressed on fragment one

    }else {
      //Back key pressed on fragment two
    }
}

步骤4:在fragment_one上声明onCreateView方法

MainActivity.Fragment_one=true;

步骤5在fragment_two上声明onCreateView方法

MainActivity.Fragment_one=false;

注:此方法仅适用于两个片段。

解决方法很简单:

如果您有一个所有片段都扩展的基片段类,那么将此代码添加到它的类中,否则创建这样一个基片段类

/* 
* called when on back pressed to the current fragment that is returned
*/
public void onBackPressed()
{
    // add code in super class when override
}

在你的Activity类中,重写onBackPressed如下:

private BaseFragment _currentFragment;

@Override
public void onBackPressed()
{
      super.onBackPressed();
     _currentFragment.onBackPressed();
}

在Fragment类中,添加你想要的代码:

@Override
public void onBackPressed()
{
    setUpTitle();
}

这个对我很有用:https://stackoverflow.com/a/27145007/3934111

@Override
public void onResume() {
    super.onResume();

    if(getView() == null){
        return;
    }

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                // handle back button's click listener
                return true;
            }
            return false;
        }
    });
}

不要实现ft.addToBackStack()方法,这样当你按下返回按钮时,你的活动就会结束。

proAddAccount = new ProfileAddAccount();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, proAddAccount);
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();