在我的MainActivity
中有一個FrameLayout
(id = fragment_container),它被onCreate
中的活動替換爲FragmentA
。 FragmentA
只包含一個按鈕並在MainActivity
中調用onClick以便用FragmentB
替換FrameLayout
。 FragmentB
包含一個RecyclerView並顯示正確。我打電話fragmentManager.popBackStack()
帶回FragmentA
。現在FragmentA
顯示在FragmentB
之上(我仍然可以與之交互)。popBackStack後仍然可見片段
爲什麼在撥打popBackStack
後不能刪除FragmentB
?
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;
}
}
爲片段A添加背景顏色。 – JpCrow
@JPCrow會不會是一個骯髒的解決方法? –
如果您願意,您可以將其添加到您的活動主題中,然後使用開發人員工具檢查該片段的透支 – JpCrow