有没有一种方法可以在安卓片段中实现onBackPressed()
,类似于我们在安卓Activity中实现的方式?
因为片段生命周期没有onBackPressed()
。有没有其他方法可以覆盖Android3.0片段中的onBackPressed()
?
发布于 2014-07-22 16:04:36
我用这种方式解决了在活动中覆盖onBackPressed
的问题。在提交之前,所有的FragmentTransaction
都是addToBackStack
:
@Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getSupportFragmentManager().popBackStack();
}
}
发布于 2017-09-26 19:34:40
在我看来,最好的解决方案是:
JAVA解决方案
创建简单的界面:
public interface IOnBackPressed {
/**
* If you return true the back press will not be taken into account, otherwise the activity will act naturally
* @return true if your processing has priority if not false
*/
boolean onBackPressed();
}
在你的活动中
public class MyActivity extends Activity {
@Override public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) {
super.onBackPressed();
}
} ...
}
最后,在您的片段中:
public class MyFragment extends Fragment implements IOnBackPressed{
@Override
public boolean onBackPressed() {
if (myCondition) {
//action not popBackStack
return true;
} else {
return false;
}
}
}
KOTLIN解
1-创建接口
interface IOnBackPressed {
fun onBackPressed(): Boolean
}
2-准备你的活动
class MyActivity : AppCompatActivity() {
override fun onBackPressed() {
val fragment =
this.supportFragmentManager.findFragmentById(R.id.main_container)
(fragment as? IOnBackPressed)?.onBackPressed()?.not()?.let {
super.onBackPressed()
}
}
}
3-在你的目标片段中实现
class MyFragment : Fragment(), IOnBackPressed {
override fun onBackPressed(): Boolean {
return if (myCondition) {
//action not popBackStack
true
} else {
false
}
}
}
发布于 2019-10-10 20:05:23
如果您使用的是androidx.appcompat:appcompat:1.1.0
或更高版本,则可以将OnBackPressedCallback
添加到片段中,如下所示
requireActivity()
.onBackPressedDispatcher
.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d(TAG, "Fragment back pressed invoked")
// Do custom work here
// if you want onBackPressed() to be called as normal afterwards
if (isEnabled) {
isEnabled = false
requireActivity().onBackPressed()
}
}
}
)
请参阅https://developer.android.com/guide/navigation/navigation-custom-back
https://stackoverflow.com/questions/5448653
复制相似问题