public class MainActivity extends Activity {
Button show ,show2;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
MyFragment fragment;
MySecondFragment mysecondfragment;
//fragment的加载可以使用id来加载,也可以使用tag来加载,在xml中给fragment中加一个tag,然后在fragmentManager.findFragmentByTag(tag)来找到。
//fragment中的button可以使用fragment的方法fragment.getView().findViewById(id)来获取fragment中的控件。
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
fragment = new MyFragment();
mysecondfragment=new MySecondFragment();
show = (Button) findViewById(R.id.click);
show2 = (Button) findViewById(R.id.click2);
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.right, fragment);
fragmentTransaction.commit();
}
});
show2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction(); //开启事物
fragmentTransaction.replace(R.id.right, mysecondfragment);
fragmentTransaction.commit(); //提交事物
}
});
}
}