Android Fragment的三种应用方式

应用方式一:动态的使用Fragment
首先是,MainActivity的布局文件activity_main.xml,该文件布局文件上面的顶部是一个TitleFragment,是一个静态声明的Fragment。
中间也是一个Fragment,但是这个Fragment是动态使用的。
最下面是四个按钮。用include标签包含外部的布局文件进来的。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:id="@+id/id_fragment_title"
        android:name="com.example.dynamicfragment.TitleFragment"
        android:layout_width="fill_parent"
        android:layout_height="45dp" />

    <include
        android:id="@+id/id_ly_bottombar"
        android:layout_width="fill_parent"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        layout="@layout/bottombar" />

    <FrameLayout
        android:id="@+id/id_content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/id_ly_bottombar"
        android:layout_below="@id/id_fragment_title" />

</RelativeLayout>

然后是,MainActivity.java文件。也是我们这个demo当中最重要的代码文件,首先是将上面的布局文件通过setContentView()加载进来.然后是通过setDefaultFragment();将默认的ContentFragment动态的加载进来。接下来就是通过我们在最下面防止的四个按钮可以随意的动态切换Fragment。

public class MainActivity extends ActionBarActivity implements OnClickListener {
    private ImageButton mTabWeixin;
    private ImageButton mTabFriend;
    private ImageButton mTabDiscover;
    private ImageButton mTabMe;

    private ContentFragment mWeiXinFragment;
    private FriendFragment mFriendFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        initView();
    }

    public void initView() {
        // 初始化控件和声明事件
        mTabWeixin = (ImageButton) findViewById(R.id.weixin);
        mTabFriend = (ImageButton) findViewById(R.id.friend);
        mTabWeixin.setOnClickListener(this);
        mTabFriend.setOnClickListener(this);

        // 设置默认的Fragment
        setDefaultFragment();
    }

    @SuppressLint("NewApi")
    private void setDefaultFragment() {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        mWeiXinFragment = new ContentFragment();
        transaction.replace(R.id.id_content, mWeiXinFragment);
        transaction.commit();
    }

    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        FragmentManager fm = getFragmentManager();
        // 开启Fragment事务
        FragmentTransaction transaction = fm.beginTransaction();
        switch (v.getId()) {
        case R.id.weixin:
            if (mWeiXinFragment == null) {
                mWeiXinFragment = new ContentFragment();
            }
            // 使用当前Fragment的布局替代id_content的控件
            transaction.replace(R.id.id_content, mWeiXinFragment);
            break;
        case R.id.friend:
            if (mFriendFragment == null) {
                mFriendFragment = new FriendFragment();
            }
            transaction.replace(R.id.id_content, mFriendFragment);
            break;
        }
        // transaction.addToBackStack();
        // 事务提交
        transaction.commit();
    }
}

从上面的代码,我们可以看出,我们可以使用FragmentManager对Fragment进行动态的加载,这里使用的replace方法
注:如果使用android3.0一下的版本,需要引入v4的包,然后Activity继承FragmentActivity,然后通过getSupportFragmentManager()获得FragmentManager对象,不过还是建议把Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改为11以上,这样就不必引入v4的包了。

代码的中间有俩个动态加载进来的Fragment,这个和静态使用ragment的声明方式是一样的,写一个继承Fragment的类,然后设置相应的布局,由于时间的关系,我这里只写了俩个Fragment,现在把这俩个的代码页贴出来:

第一个Fragment和他相应的布局文件:

public class ContentFragment extends Fragment {
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState)  
    {  
        return inflater.inflate(R.layout.fragment_content, container, false);  
    }  
}
<?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:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        android:gravity="center"  
        android:text="weixin"  
        android:textSize="20sp"  
        android:textStyle="bold" />  

</LinearLayout>

应用方式二:静态使用

这是使用Fragment最简单的一种方式,把Fragment当成普通的控件,直接写在Activity的布局文件中,用布局文件调用Fragment。

步骤:

1、继承Fragment,重写onCreateView决定Fragment布局。
2、在Activity中声明此Fragment,就当和普通的View一样。
下面展示一个例子(我使用俩个Fragment作为Activity的布局,一个Fragment用于标题布局,一个Fragment用于内容布局)。
TitleFragment的布局文件,在这里我们可以看出,我们可以每个Fragment当中进行单独的布局:

下面就是主Activity以及他的布局文件

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.activity_main);  
    }
}

activity_main.xml布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.staticfragment.MainActivity" >

       <fragment 
           android:name="com.example.staticfragment.TitleFragment"
           android:id="@+id/title"
           android:layout_height="45dp"
           android:layout_width="match_parent"/>
       <fragment 
           android:layout_below="@id/title"
           android:name="com.example.staticfragment.ContentFragment"
           android:id="@+id/content"
           android:layout_height="fill_parent"    
           android:layout_width="fill_parent"/>

</RelativeLayout>

TitleFragment.java文件,在这里我们能够看到,可以在各个Fragment当中进行独立的初始化空间并且处理按钮之类的事件,减轻了Activity的负担,我们在Activity中就没有必要写一大推初始化控件和事件响应的代码了,这样就使我们的代码看上去更加的简洁了,可读性大大提高了。
如果引用:

public class TitleFragment extends Fragment {

    private ImageButton mButton;
    @SuppressLint("NewApi")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.title_fragment, container, false);
        mButton = (ImageButton)view.findViewById(R.id.id_title_left_btn);
        mButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(),   "i am an ImageButton in TitleFragment ! ",   Toast.LENGTH_SHORT).show();                   
            }
        });
        return view;
    }

}

title_fragment.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="45dp"
    android:background="@drawable/title_bar" >

    <ImageButton
        android:id="@+id/id_title_left_btn"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_centerVertical="true"
        android:background="@drawable/showleft_selector" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="我不是微信"
        android:textColor="#fff"
        android:textSize="20sp"
        android:textStyle="bold" />

</RelativeLayout>

同理还有ContentFragment的布局文件content_fragment.xml

<?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:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="使用Fragment做主面板"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>

同理还有ContentFragment.java文件

public class ContentFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.content_fragment, container,false);
    }

}

应用三:使用ViewPager
把fragment组装成一个数组,使用setAdapter方法把fragment添加到viewpager

详细代码如:
首先定义标题,根据标题的长度创建对应的fragment

public class ViewPagerActivity extends FragmentActivity {
    private String[] mTitles = new String[] { "简介", "评价", "相关" };  
    //创建viewpager
    private ViewPager mViewPager;
    //定义数据数组
    private TabFragment[] mDatas = new TabFragment[mTitles.length];
    //定义标题控件
    List<ColorChangeView> mTabs = new ArrayList<ColorChangeView>();

    private FragmentPagerAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewpager);
        initViews();
        initDatas();
        initEvenvts();
    }



    private void initViews() {
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
    }



    private void initDatas() {
        for (int i = 0; i < mTitles.length; i++) {
            mDatas[i] = TabFragment.newInstance(mTitles[i]);
        }


        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mTitles.length;
            }

            @Override
            public Fragment getItem(int position) {
                return mDatas[position];
            }
        };

        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
    }



    private void initEvenvts() {
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (positionOffset > 0) {
                    ColorChangeView left = mTabs.get(position);
                    left.setDirection(ColorChangeView.DIRECTION_LEFT);
                    left.setProgress(1-positionOffset);
                    ColorChangeView right = mTabs.get(position+1);
                    right.setDirection(ColorChangeView.DIRECTION_RIGHT);
                    right.setProgress(positionOffset);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }
}

对应的布局

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal" >

        <com.android.view.colortextview.ColorChangeView
            android:id="@+id/id_tab_01"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            koo:progress="1"
            koo:text="简介"
            koo:text_change_color="#ffff0000"
            koo:text_origin_color="#ff000000"
            koo:text_size="18sp" />

        <com.android.view.colortextview.ColorChangeView
            android:id="@+id/id_tab_02"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            koo:text="评价"
            koo:text_change_color="#ffff0000"
            koo:text_origin_color="#ff000000"
            koo:text_size="18sp" />

        <com.android.view.colortextview.ColorChangeView
            android:id="@+id/id_tab_03"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            koo:text="相关"
            koo:text_change_color="#ffff0000"
            koo:text_origin_color="#ff000000"
            koo:text_size="18sp" />

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/id_viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </android.support.v4.view.ViewPager>

</LinearLayout>

对应的fragment

public class TabFragment extends Fragment {
    public static final String TITLE = "title";
    private String mTitle = "Defaut Value";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mTitle = getArguments().getString(TITLE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        TextView tv = new TextView(getActivity());
        tv.setTextSize(60);
        Random r = new Random();
        tv.setBackgroundColor(Color.argb(r.nextInt(120), r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        tv.setText(mTitle);
        tv.setGravity(Gravity.CENTER);
        return tv;
    }

    public static TabFragment newInstance(String title) {
        TabFragment tabFragment = new TabFragment();
        Bundle bundle = new Bundle();
        bundle.putString(TITLE, title);
        //保存标题信息
        tabFragment.setArguments(bundle);
        return tabFragment;
    }
}

—————————————————–
(java 架构师全套教程,共760G, 让你从零到架构师,每月轻松拿3万)
请先拍 购买地址, 下载请用百度盘
目录如下:
01.高级架构师四十二个阶段高
02.Java高级系统培训架构课程148课时
03.Java高级互联网架构师课程
04.Java互联网架构Netty、Nio、Mina等-视频教程
05.Java高级架构设计2016整理-视频教程
06.架构师基础、高级片
07.Java架构师必修linux运维系列课程
08.Java高级系统培训架构课程116课时
(送:hadoop系列教程,java设计模式与数据结构, Spring Cloud微服务, SpringBoot入门)

01高级架构师四十二个阶段高内容:
这里写图片描述
这里写图片描述
—————————————————–

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lovoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值