Android开发中Fragment的使用

来源:互联网 发布:巴西人种知乎 编辑:程序博客网 时间:2024/06/08 14:07

Fragment 表现 Activity 中用UI的一个行为或者一部分. 可以组合多个fragment放在一个单独的activity中来创建一个多界面区域的UI,并可以在多个activity里重用某一个fragment.把fragment 想象成一个activity的模块化区域, 有它自己的生命周期, 接收属于它的输入事件, 并且可以在activity运行期间添加和删除.

  Fragment 必须总是被嵌入到一个activity中, 它们的生命周期直接被其所属的宿主activity的生命周期影响. 例如, 当activity被暂停,那么在其中的所有fragment也被暂停; 当activity被销毁, 所有隶属于它的fragment也被销毁. 然而,当一个activity正在运行时(处于resumed状态), 我们可以独立地操作每一个fragment, 比如添加或删除它们. 当处理这样一个fragment事务时, 也可以将它添加到activity所管理的back stack -- 每一个activity中的back stack实体都是一个发生过的fragment事务的记录. back stack允许用户通过按下 BACK 按键从一个fragment事务后退(往后导航).


学习Android已经有几个月了,前几天做的项目中使用到Fragment的知识,就上网搜索了一下,这里是我整理出来的关于Fragment的使用。

1.效果图(当点击下方菜单栏任意图标时,图标和下方的字体颜色都会随着变化)



2.Mainactivity的代码

package com.stx.fleshfruit.viewpager;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import com.stx.fleshfruit.fragment.Fragment_home;import com.stx.fleshfruit.fragment.Fragment_favorite;import com.stx.fleshfruit.fragment.Fragment_shopcart;import com.stx.fleshfruit.fragment.Fragment_personal;import com.stx.fleshfruit.view.MyTabView.onTabSelectListener;public class MainActivity extends FragmentActivity implementsonTabSelectListener {private MyViewPager mvp;private MyFragmentPagerAdapter mAdapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mvp = (MyViewPager) findViewById(R.id.mvp);mAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());mvp.setAdapter(mAdapter);}private class MyFragmentPagerAdapter extends FragmentPagerAdapter {public MyFragmentPagerAdapter(FragmentManager fm) {super(fm);}@Overridepublic Fragment getItem(int position) {Fragment fragment = null;switch (position) {case 0:fragment = new Fragment_home();break;case 1:fragment = new Fragment_favorite();break;case 2:fragment = new Fragment_shopcart();break;case 3:fragment = new Fragment_personal();break;}return fragment;}@Overridepublic int getCount() {return 4;}}@Overridepublic void onTabSelect(int position) {mvp.setCurrentItem(position);}}
2.main xml文件

<LinearLayout 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"    android:orientation="vertical" >    <com.stx.fleshfruit.viewpager.MyViewPager        android:id="@+id/mvp"        android:layout_width="fill_parent"        android:layout_height="0dp"        android:layout_weight="1" >    </com.stx.fleshfruit.viewpager.MyViewPager>    <com.stx.fleshfruit.view.MyTabView        android:id="@+id/myTab"        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <com.stx.fleshfruit.view.MyTabView            android:id="@+id/MyTabView01"            android:layout_width="fill_parent"            android:layout_height="wrap_content" >        </com.stx.fleshfruit.view.MyTabView>    </com.stx.fleshfruit.view.MyTabView></LinearLayout>
3.收藏界面Fragment_favorite

package com.stx.fleshfruit.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment_favorite extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.pager_favorite, container, false);}}
3.首页Fragment_home

package com.stx.fleshfruit.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment_favorite extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.pager_favorite, container, false);}}package com.stx.fleshfruit.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment_favorite extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.pager_favorite, container, false);}}
4.个人中心Fragment_personal

package com.stx.fleshfruit.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment_personal extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.pager_person, container, false);}}
5.Fragment_shopcart购物车
package com.stx.fleshfruit.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment_personal extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.pager_person, container, false);}}
6.对菜单栏下方图标颜色及字体颜色随着点击时而变化代码MyTabView

package com.stx.fleshfruit.view;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.content.Context;import android.graphics.Color;import android.util.AttributeSet;import android.view.LayoutInflater;import android.view.View;import android.widget.LinearLayout;import android.widget.RadioButton;public class MyTabView extends LinearLayout implements View.OnClickListener {private onTabSelectListener listener;private List<RadioButton> views;private int currentPosition;private List<Integer> selectImages = new ArrayList<Integer>();private List<Integer> unSelectImages = new ArrayList<Integer>();public MyTabView(Context context, AttributeSet attrs) {super(context, attrs);init();}public void init() {View contentView = LayoutInflater.from(getContext()).inflate(R.layout.my_tab, this);views = new ArrayList<RadioButton>();views.add((RadioButton) contentView.findViewById(R.id.menu_home));views.add((RadioButton) contentView.findViewById(R.id.menu_favorite));views.add((RadioButton) contentView.findViewById(R.id.menu_gouwuche));views.add((RadioButton) contentView.findViewById(R.id.menu_personal));// 设置点击时菜单栏图标selectImages.add(R.drawable.home);selectImages.add(R.drawable.favorite);selectImages.add(R.drawable.gouwuche1);selectImages.add(R.drawable.person);// 设置没有点击时菜单栏图标unSelectImages.add(R.drawable.home_1);unSelectImages.add(R.drawable.favorite_1);unSelectImages.add(R.drawable.gouwuche_1);unSelectImages.add(R.drawable.person_1);for (RadioButton rb : views) {rb.setOnClickListener(this);}Activity activity = (Activity) getContext();if (!(activity instanceof onTabSelectListener)) {throw new IllegalStateException("Activity must implement TabSelectView OnTableSelectListener.");}listener = (onTabSelectListener) activity;}public interface onTabSelectListener {public void onTabSelect(int position);}// 设置点击监听事件@Overridepublic void onClick(View v) {currentPosition = getSelectPosition(v);setPosition(currentPosition);listener.onTabSelect(currentPosition);}private void setPosition(int position) {for (int i = 0; i < views.size(); i++) {if (position == i) {// 对菜栏下方图标级字体颜色的变化views.get(i).setTextColor(getContext().getResources().getColor(R.color.checked));views.get(i).setCompoundDrawablesWithIntrinsicBounds(null,getResources().getDrawable(selectImages.get(i)), null,null);} else {views.get(i).setTextColor(Color.GRAY);views.get(i).setCompoundDrawablesWithIntrinsicBounds(null,getResources().getDrawable(unSelectImages.get(i)),null, null);}}}private int getSelectPosition(View v) {for (int i = 0; i < views.size(); i++) {if (views.get(i) == v) {return i;}}return 0;}}
7.MyViewPager.activity代码

package com.stx.fleshfruit.viewpager;import android.content.Context;import android.support.v4.view.ViewPager;import android.util.AttributeSet;import android.view.MotionEvent;public class MyViewPager  extends ViewPager{public MyViewPager(Context context, AttributeSet attrs) {super(context, attrs);}@Overridepublic boolean onInterceptTouchEvent(MotionEvent arg0) {return false;}@Overridepublic boolean onTouchEvent(MotionEvent arg0) {return false;}}
8.My_tab。xml文件

<LinearLayout 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"    android:orientation="vertical"     android:background="#ededed">    <RadioGroup        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        android:background="#ffffff" >        <RadioButton            android:id="@+id/menu_home"            style="@style/myTabStyle"            android:drawableTop="@drawable/home_1"            android:text="首页"             android:textColor="#9c9c9c"/>        <RadioButton            android:id="@+id/menu_favorite"            style="@style/myTabStyle"            android:drawableTop="@drawable/favorite_1"            android:text="收藏"            android:textColor="#9c9c9c" />        <RadioButton            android:id="@+id/menu_gouwuche"            style="@style/myTabStyle"            android:drawableTop="@drawable/gouwuche_1"            android:text="购物篮"             android:textColor="#9c9c9c"/>        <RadioButton            android:id="@+id/menu_personal"            style="@style/myTabStyle"            android:drawableTop="@drawable/person_1"            android:text="我"             android:textColor="#9c9c9c"/>    </RadioGroup></LinearLayout>
9.收藏界面的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:background="#ededed"    android:orientation="vertical" >    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="收藏" /></LinearLayout>
10.其他xml文件都是一样的










1 0