是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?
因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?
是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?
因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?
当前回答
@Override
public void onResume() {
super.onResume();
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
replaceFragmentToBackStack(getActivity(), WelcomeFragment.newInstance(bundle), tags);
return true;
}
return false;
}
});
}
其他回答
试试这个,如果你真的想在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();
}
}
}```
这些都不容易实现,也不会以最佳方式发挥作用。
片段有一个方法调用onDetach来完成这项工作。
@Override
public void onDetach() {
super.onDetach();
PUT YOUR CODE HERE
}
这个就行了。
我有同样的问题,我为它创建了一个新的侦听器,并在我的片段中使用。
1 -你的活动应该有一个监听器接口和一个监听器列表
你应该实现添加和删除监听器的方法
你应该重写onBackPressed方法来检查监听器是否使用了背按
public class MainActivity ... {
/**
* Back press listener list. Used for notifying fragments when onBackPressed called
*/
private Stack<BackPressListener> backPressListeners = new Stack<BackPressListener>();
...
/**
* Adding new listener to back press listener stack
* @param backPressListener
*/
public void addBackPressListener(BackPressListener backPressListener) {
backPressListeners.add(backPressListener);
}
/**
* Removing the listener from back press listener stack
* @param backPressListener
*/
public void removeBackPressListener(BackPressListener backPressListener) {
backPressListeners.remove(backPressListener);
}
// Overriding onBackPressed to check that is there any listener using this back press
@Override
public void onBackPressed() {
// checks if is there any back press listeners use this press
for(BackPressListener backPressListener : backPressListeners) {
if(backPressListener.onBackPressed()) return;
}
// if not returns in the loop, calls super onBackPressed
super.onBackPressed();
}
}
4 -你的片段必须实现接口的背压
5 -你需要添加片段作为背按的监听器
如果片段使用这个背压,你应该从onBackPressed返回true
7 -重要-你必须删除片段从列表onDestroy
public class MyFragment extends Fragment implements MainActivity.BackPressListener {
...
@Override
public void onAttach(Activity activity) {
super.onCreate(savedInstanceState);
// adding the fragment to listener list
((MainActivity) activity).addBackPressListener(this);
}
...
@Override
public void onDestroy() {
super.onDestroy();
// removing the fragment from the listener list
((MainActivity) getActivity()).removeBackPressListener(this);
}
...
@Override
public boolean onBackPressed() {
// you should check that if this fragment is the currently used fragment or not
// if this fragment is not used at the moment you should return false
if(!isThisFragmentVisibleAtTheMoment) return false;
if (isThisFragmentUsingBackPress) {
// do what you need to do
return true;
}
return false;
}
}
有一个Stack来代替ArrayList,以便能够从最新的片段开始。在向后台堆栈添加片段时也可能出现问题。所以你需要检查碎片是否可见,而使用背压。否则,其中一个片段将使用事件,并且最新的片段将不会在背按时关闭。
我希望这能解决所有人的问题。
在片段的onCreate方法中添加以下内容:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
//Handle the back pressed
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}
public class MyActivity extends Activity {
protected OnBackPressedListener onBackPressedListener;
public interface OnBackPressedListener {
void doBack();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}
@Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}
@Override
protected void onDestroy() {
onBackPressedListener = null;
super.onDestroy();
}
}
在你的片段中添加以下内容,不要忘记实现mainactivity的接口。
public class MyFragment extends Framgent implements MyActivity.OnBackPressedListener {
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((MyActivity) getActivity()).setOnBackPressedListener(this);
}
@Override
public void doBack() {
//BackPressed in activity will call this;
}
}