我正在尝试安卓片段,我无法理解这一点;请帮忙
public class MainActivity extends FragmentActivity {
private static final String TAG = "MyActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container) !=null) {
if(savedInstanceState!=null){
return ;
}
ArticleFragment first_fragment = new ArticleFragment();
HeadlineFragment second_fragment = new HeadlineFragment();
first_fragment.setArguments(getIntent().getExtras());
second_fragment.setArguments(getIntent().getExtras());
FragmentTransaction manager=getSupportFragmentManager().beginTransaction();
manager.add(R.id.fragment_container, first_fragment,"first");
manager.add(R.id.yo, second_fragment,"second");
manager.commit();
}
}
现在我想在按下按钮时删除second_fragment并将其替换为另一个按钮。所以我试过这个
if(getSupportFragmentManager().findFragmentByTag("second")!=null) {
Log.d(TAG,"found");
abc newFragment = new abc();
Bundle args = new Bundle();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(getSupportFragmentManager().findFragmentByTag("second"));
transaction.add(R.id.fragment_container,newFragment,"third");
transaction.addToBackStack(null);
transaction.commit();
}
但是当我一次又一次按下该按钮时,if条件通过。 这有什么不对?
答案 0 :(得分:0)
不要删除和添加。只需用新的片段替换第二个片段。你将完成。