在布局文件中,使用linearlayout实现fragment的容器
public class MainfragmentActivity extends FragmentActivity{
// Discoverfragment discover;// Mefragment me;
Sportfragment sport;
//
// private Button btn1;
// private Button btn2;
// private Button btn3;
int currentfragmentIndex=0;
int clickButtonIndex=0;
Button[] btnArray=new Button[3];
Fragment[] fragment=new Fragment[3];
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
try {
setContentView(R.layout.main_fragment);
setview();
setlistener();
btnArray[0].setSelected(true);
sport=new Sportfragment();
FragmentManager manner=getSupportFragmentManager();
FragmentTransaction action=manner.beginTransaction();
action.add(R.id.fragment_container, sport);
action.commit();
fragment[0]=sport;
fragment[1]=new Discoverfragment();
fragment[2]=new Mefragment();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setlistener() {
Myclicklistener my=new Myclicklistener();
for (Button btn:btnArray) {
btn.setOnClickListener(my);
}
}
private void setview() {
btnArray[0]=(Button) findViewById(R.id.btn_main_fragment_sport);
btnArray[1]=(Button) findViewById(R.id.btn_main_fragment_discover);
btnArray[2]=(Button) findViewById(R.id.btn_main_fragment_me);
}
class Myclicklistener implements OnClickListener{
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_main_fragment_sport:
clickButtonIndex=0;
break;
case R.id.btn_main_fragment_discover:
clickButtonIndex=1;
break;
case R.id.btn_main_fragment_me:
clickButtonIndex=2;
break;
}
if (clickButtonIndex!=currentfragmentIndex) {
FragmentManager manner=getSupportFragmentManager();
FragmentTransaction action=manner.beginTransaction();
action.hide(fragment[currentfragmentIndex]);
Fragment showfragment=fragment[clickButtonIndex];
if (!showfragment.isAdded()) {
action.add(R.id.fragment_container, showfragment);
}
action.show(showfragment);
action.commit();
}
btnArray[currentfragmentIndex].setSelected(false);
btnArray[clickButtonIndex].setSelected(true);
currentfragmentIndex=clickButtonIndex;
}
}
}