Android基础篇之浅谈Fragment(app包)

博主再和大家分享之前,先要和大家讲一下Fragment

什么是fragment,它的定义什么的我就不用说了,百度什么都有,我只举个例子,像微信能够在主界面左右滑动切换界面,那就是fragemnt,而我们在编写fragment的时候 有两种包可以导入,如图:

(博主用的是AS开发 )


博主在这里分享一下app包的fragment编写,废话不多说,直接上代码:

首先建立两个fragment的布局文件:

接下来在布局文件里面添加一个textview(另外一个fragemnt布局也是如此):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:text="第一个碎片"
       android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
然后调到fragemnt里面 让fragment继承android.app包里面的fragemnt;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
        
    }

(这是建立fragment时候的代码 博主把它修改一下,便于以后在fragment里面进行别的操作)

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment1, container,false);
        //中间进行初始化操作,例如findviewbyid()等等;但是return要放在在最后

        textView = (TextView) view.findViewById(R.id.text);

  return view; }

在fragment里面,进行findID要加上view(代码中的白色字体)才能敲出来;

好,到这里第一个碎片基本上Ok了,然后按图索骥,写完第二个碎片;

然后跳到mainactivity里面编写“桥梁”,同样 ,上图:

先设置两个碎片变量:
    private Fragment1 fragment1;
    private Fragment2 fragment2;
然后找到两个按钮的id:
btn1 = (Button) findViewById(R.id.thefirstfrg);
btn2 = (Button) findViewById(R.id.thesecondfrg);
为两个按钮设置点击事件(博主使得Activity 继承 onclick接口,使得重写onclick方法,便于点击事件集中处理):
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);

然后我设置软件进来要显示的第一个fragemnt

private void thefristfragment(){};

在onclick方法里面实现switch选择方法,通过判断点击的id,来判断是点击了哪一个按钮:

switch (v.getId()){
      case R.id.按钮的id :
        break;
}
重点来了:
//这两步很重要,就类似高手开辟空间一样,开辟了才能放东西
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        //这里实例化fragment1
        fragment1 = new Fragment1();
        //有点英语基础的人都知道replace是代替的意思
        //其实也就是说用fragment1 代替掉r.id.fragment这个位置
        transaction.replace(R.id.fragment,new Fragment1());
        //封闭空间
        transaction.commit();

然后在switch里面同样这么写,然后。。。。看效果:


下载源码


猜你喜欢

转载自blog.csdn.net/jonsonbob/article/details/60904075