我創建了兩個Fragment,在MainAcitivity裡分別用兩個按鈕去啟動它們,代碼如下:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.btn1);
Button button=(Button)findViewById(R.id.btn2);
btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
FragmentManager fm=getFragmentManager();
Fragment fragment=fm.findFragmentById(R.id.linear1);
if(fragment==null)
{
fragment=new frag();
fm.beginTransaction()
.add(R.id.linear1,fragment)
.commit();
}
}
});
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
FragmentManager fm=getFragmentManager();
Fragment fragment=fm.findFragmentById(R.id.linear1);
if(fragment==null)
{
fragment=new frag2();
fm.beginTransaction()
.replace(R.id.linear1,fragment)
.commit();
}
}
});
}
但是我在運行的時候發現按了按鈕btn後顯示了第一個Fragment,但是再按按鈕button是就沒有任何反應了,第二個Fragment沒有顯示出來,請問這是怎麼回事?要實現Fragment的替換,我應該如何去做?
參考 http://longshuai2007.blog.163.com/blog/static/142094414201362631129902/