在我的MainActivity
中,FrameLayout
(id = fragment_container)被onCreate
中FragmentA
的活动取代。 FragmentA
只包含一个按钮,并在MainActivity
中调用onClick,以便将FrameLayout
替换为FragmentB
。 FragmentB
包含RecyclerView并正确显示。我致电fragmentManager.popBackStack()
以取回FragmentA
。现在FragmentA
显示在FragmentB
之上(我仍然可以与之交互)。
调用FragmentB
后,为什么popBackStack
没有删除?
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private FragmentManager fragmentManager;
@Override
public void onBackPressed() {
fragmentManager.popBackStack();
}
@Override
public void onClick(View view) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new FragmentB());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentA fragment = FragmentA.getInstance(this); //register OnClickListener
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
//...
}
FragmentA
public class FragmentA extends Fragment {
private View.OnClickListener onClickListener;
public FragmentA() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(onClickListener);
return view;
}
public static FragmentA getInstance(View.OnClickListener onClickListener) {
FragmentA fragmentA = new FragmentA();
fragmentA.setOnClickListener(onClickListener);
return fragmentA;
}
private void setOnClickListener(View.OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
}
FragmentB
public class FragmentB extends Fragment {
//...
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.FragmentB, container, true);
//manipulating Views...
//...
return view;
}
}
答案 0 :(得分:0)
问题出在FragmentB
课程中。你不应该传递参数attachToRoot=true
。
请改为尝试:
public class FragmentB extends Fragment {
//...
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//don't pass true
View view = inflater.inflate(R.layout.FragmentB, container, false);
//manipulating Views...
//...
return view;
}
}
答案 1 :(得分:0)
@Override
public void onBackPressed() {
fragmentManager.popBackStackImmediate();
}
与popBackStack()类似,但在调用内部立即执行操作。这就像之后调用executePendingTransactions()一样。