我创建了两个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/
fm.findFragmentById(R.id.linear1);
当你点击第一次的时候,上面的代码返回的是一个null。
这个时候linear1显示的就是第一个fragment,
点击第二次的时候,还是通过这个后去fragment实例,当然就不是null了。
所以里面的方法就不执行了。
第二个find的id有没有写错