编辑:
这不是一个错误,而更像是片段框架中的缺陷。对于这个问题更好的答案是由 @Arcao 提供的。
---- 原始帖子 ----
实际上这是支持包中的 已知错误(编辑:实际上不是一个错误,请参见 @alex-lockwood 的评论)。在错误报告的评论中发布了一个解决方法,即修改 DialogFragment 的源代码,如下所示:
public int show(FragmentTransaction transaction, String tag) {
return show(transaction, tag, false);
}
public int show(FragmentTransaction transaction, String tag, boolean allowStateLoss) {
transaction.add(this, tag);
mRemoved = false;
mBackStackId = allowStateLoss ? transaction.commitAllowingStateLoss() : transaction.commit();
return mBackStackId;
}
注意,这只是一个巨大的hack。我实际上是制作了自己的对话框片段,可以从原片段中注册。当另一个对话框片段执行操作(例如被解除显示)时,它会告诉任何监听器它正在消失。我是这样做的:
public static class PlayerPasswordFragment extends DialogFragment{
Player toJoin;
EditText passwordEdit;
Button okButton;
PlayerListFragment playerListFragment = null;
public void onCreate(Bundle icicle){
super.onCreate(icicle);
toJoin = Player.unbundle(getArguments());
Log.d(TAG, "Player id in PasswordFragment: " + toJoin.getId());
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle icicle){
View v = inflater.inflate(R.layout.player_password, container, false);
passwordEdit = (EditText)v.findViewById(R.id.player_password_edit);
okButton = (Button)v.findViewById(R.id.ok_button);
okButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
passwordEntered();
}
});
getDialog().setTitle(R.string.password_required);
return v;
}
public void passwordEntered(){
playerListFragment.joinPlayer(toJoin, passwordEdit.getText().toString());
dismiss();
}
public void registerPasswordEnteredListener(PlayerListFragment playerListFragment){
this.playerListFragment = playerListFragment;
}
public void unregisterPasswordEnteredListener(){
this.playerListFragment = null;
}
}
现在我有一种方法可以在发生事情时通知PlayerListFragment。请注意,适当调用unregisterPasswordEnteredListener非常重要(在上述情况下,每当PlayerListFragment“消失”时),否则该对话框片段可能会尝试在已不存在的侦听器上调用函数。
Activity
类中不存在onResumeFragments()
方法。如果您正在使用基本的Activity
,则应该使用onPostResume()
方法。 - Alex Lockwood