我在我的活动中使用了两个片段。最初我将向活动添加一个片段。然后在第一个片段中使用侦听器,我想用第二个片段替换它。我根据我的理解尝试过,但它没有取代。它显示两个片段重叠。
Here is my code:
// MainActivity
public class MainActivity extends Activity {
Fragment Fragment_one;
Button one;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//one=(Button) findViewById(R.id.button1);
//one.setOnClickListener(new View.OnClickListener() {
//@Override
//public void onClick(View arg0) {
// TODO Auto-generated method stub
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_one=new Fragment1();
tran.add(R.id.fragment_container, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
//}
//});
}
}
//fragment code
public class Fragment1 extends Fragment{
Button add;
Fragment2 fragment_two;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return super.onCreateView(inflater, container, savedInstanceState);
View view=inflater.inflate(R.layout.fragment_1, container,false);
add=(Button) view.findViewById(R.id.button1);
fragment_two =new Fragment2();
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction t=getActivity().getFragmentManager().beginTransaction();
t.remove( new Fragment1());
t.replace(R.id.fragment1, fragment_two);t.addToBackStack(null);
t.commit();
//t.addToBackStack(null);
}
});
return view;
}
}