您的位置:首页 > 移动开发 > Android开发

fragment个人使用总结

2017-05-16 20:28 183 查看
以下做一些我在使用fragment的时候的总结:

一.两种添加方法:

  1.静态加载:就像一般控件在xml文件中使用的方法一样,给它配置一下属性,然后肯定有不一样的地方啦:继承fragment,在它的setContentView方法里决定他的布局,然后...就没有然后了.(就像用activity一样,虽然它跟activity不一样)

  2.动态加载:说的很不方便,放伪代码吧(看注释)这里不仅是动态加载,还有一些fragment的常用方法

public class MainActivity extends AppCompatActivity{

private firstFragment fF;
private professionFragment pF;
private courseFragment cF;

private Button button1;
private Button button2;
private Button button3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.first_button);
button2 = (Button) findViewById(R.id.college_button);
button3 = (Button) findViewById(R.id.professional_button);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
setFragment();
}

@Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();//一定要记得初始化这个方法,
//用来管理fragment的
hideFragment(ft);
switch (v.getId()){
case R.id.first_button:
if(fF == null){
fF = new firstFragment();
ft.add(R.id.content, fF);//这里的R.id.content是一个framelayout布局,用来装载动态添加的fragment
//不然fragment放哪了
 }else{
ft.show(fF);//展示被隐藏的fragment
}
break;
case R.id.college_button:
if(cF == null){
cF = new courseFragment();
ft.add(R.id.content, cF);
}else{
ft.show(cF);
}
break;
case R.id.professional_button:
if(pF == null){
pF = new professionFragment();
ft.add(R.id.content, pF);
}else{
ft.show(pF);
}
break;
}
ft.commit();
}

private void hideFragment(FragmentTransaction fragmentTransaction){
if (fF != null){
fragmentTransaction.hide(fF);//用来隐藏fragment,并不会销毁fragment
}
if (pF != null){
fragmentTransaction.hide(pF);
}
if (cF != null){
fragmentTransaction.hide(cF);
}
}

private void setFragment() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
fF = new firstFragment();
ft.replace(R.id.content, fF);//替换操作,其实是remove+add操作的组合
ft.commit();//不能忘!!!注册
}

}
三.activity与fragment的通信(接口)

我这里给出自己写的伪代码,不好意思啊,因为没时间写例子

public class MainActivity extends AppCompatActivity implements courseFragment.Myinterface{

//你的activity里的代码

@Override
    public void open(String id) {
       //这里接受到了fragment传的数据
    }
}
public class courseFragment extends Fragment {

    public Myinterface myinterface;

public void fun(){
//这里用你要传到activity的数据
myinterface.open(id);
}

public interface Myinterface{
       public void open(String id);
    }
}
四.回退栈FragmentTransaction.addToBackStack(String) 使用这个方法可以将回退的fragment加到一个栈中,并不是销毁,只是

[b]   视图销毁而已,这样可以避免不断创建fragment.

[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android