ragement:碎片,ui的一个部分或行为,类似于activity,需嵌入在activity中,一个activity包含多个fragement,可以最大程度适配不同尺寸的手机activity的一部分Oncreate:全局变量赋值,初始化信息。在此之前,已经创建Onattach:fragement绑定activity
Oncreate:
oncreateView:给fragement设置页面
OnactivityCreated:
ondestroyView()
Ondestroy()
Ondetach()
Fragement使用步骤:创建fragement布局文件继承fragement类自定义fragement,实现相关方法Layoutinflate:布局加载器控件?
动态添加:直接在布局文件中引用
静态添加:
public class SecondFragment extends FragmentActivity implements OnClickListener,OnBackgroundChangeListener{ private Button btnadd; @Override protected void onCreate(Bundle arg0) { // TODO Auto-generated method stub super.onCreate(arg0); setContentView(R.layout.second_fragment); btnadd=(Button) findViewById(R.id.addfragment); findViewById(R.id.addfragment).setOnClickListener(this); findViewById(R.id.delfragment).setOnClickListener(this); findViewById(R.id.hidefragment).setOnClickListener(this); findViewById(R.id.showfragment).setOnClickListener(this); findViewById(R.id.btnChange).setOnClickListener(this); } @Override public void onClick(View v) { FragmentTransaction ft; switch(v.getId()){ case R.id.addfragment: //添加fragment道activity FragmentManager fm=getSupportFragmentManager(); ft=fm.beginTransaction(); ft.add(R.id.fragmentContainer, new FirstFragement(), "chaos"); ft.commit(); break; case R.id.delfragment: //ft=getSupportFragmentManager().beginTransaction(); Fragment f=getSupportFragmentManager().findFragmentByTag("chaos"); ((FirstFragement)f).setOnBackgroundChangeListener(this); //ft.remove(f); //ft.commit(); break; case R.id.showfragment: ft=getSupportFragmentManager().beginTransaction(); Fragment sf=getSupportFragmentManager().findFragmentByTag("chaos"); ft.show(sf); ft.commit(); break; case R.id.hidefragment: ft=getSupportFragmentManager().beginTransaction(); Fragment hf=getSupportFragmentManager().findFragmentByTag("chaos"); ft.hide(hf); ft.commit(); break; case R.id.replacefragment: ft=getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fragmentContainer, new FirstFragement(), "chaoss"); ft.commit(); break; case R.id.btnChange: FirstFragement ff=(FirstFragement) getSupportFragmentManager().findFragmentByTag("chaos"); if(ff==null){ return; } ImageView img=(ImageView) findViewById(R.id.img); img.setImageResource(R.drawable.bbe609315da7a9bfa65df713e7c168e0); break; default: break; } } public void onBackgroundChange(){ btnadd.setBackgroundResource(R.drawable.bc494385774b8343123c5697ebeaeb9); } }