Android中如何使用Fragment打造出炫酷效果

来源:互联网 发布:php游戏开发教程 编辑:程序博客网 时间:2024/04/26 04:37

作为一个Android开发人员,应该没有谁不知道Fragment!其重要性可想而知了!不多说,先上图

实例一(使用ListFragment和Fragment结合实现):
Fragment

实例一源代码代码下载地址

实例二(Fragment结合RadioButton)
Fragment

实例二源代码下载地址

Fragment

Fragment文件下载地址

      • Fragment的特征
      • Fragment常用知识点
      • Fragment的生命周期
      • 创建Fragment
      • 实例一
          • MainActivity代码
          • FoodContentjava
          • FoodListFragmentjava
          • FoodDetailFragmentjava
          • mainxml代码
      • 实例二
          • MainActivity代码
          • activity_mainxml
          • stylesxml代码
          • 选择器代码

Fragment的特征:

Fragment必须嵌入到Activity中使用。因此,即使Fragment拥有自己的生命周期,也会收到它所在的Activity的生命周期的控制。当Activity暂停时,Activity中所有的Fragment都会暂停;当Activity被销毁时,其中所有的Fragment将会被销毁;只有Activity处于活动状态时,程序员才可以通过方法独立地操作Fragment。

  • Fragment总是作为Activity界面组成部分。Fragment可调用getActivity()方法获取它所在的Activity。Activity可调用 FragmentManager的findFragmentById()或者findFragmentBuTag()方法来获取Fragment

  • 在Activity运行过程中,可调用FragmentManager的add(),remove(),replace()方法动态添加,移除,修改。

  • 一个Activity可以同时拥有多个Fragment,一个Fragment也可以被多个Activity复用。

  • Fragment可以响应自己的输入事件,并拥有自己的生命周期,但生命周期被所属的Activity的生命周期控制。

    Fragment常用知识点:

  • Fragment和所属Activity的通讯如何处理!

    1. Activity向Fragment传递数据:在Activity中创建Bundle数据包,并调用Fragment的setArgument(Bundle bundle)方法将Bundle数据传递给Fragment.

    2. Fragment向Activity传递数据:Fragment中定义一个内部回调接口,再让包含该Fragment的Activity实现该回掉接口,这样就能将Fragment的数据传给Activity了!

  • 如何将Fragment添加到Activity中:

    1. 在布局文件中使用<fragment…/>元素添加Fragment,<fragment…/>元素的android:name属性指定Fragment的实现类

    2. 在Java代码中通过FragmentTransaction对象的add()方法来添加Fragment.

  • Activity获取它包含的Fragment:用Fragment的getActivity();

  • Fragment获取它所在的Activity:调用关联的FragmentMangager的findFragmentById(int id)或者fingFragmentByTag(String tag)方法即可获取Fragment。

  • Fragment管理

    FragmentManager可以实现以下几方面的功能:

    1. 使用 findFragmentById(int id)或fingFragmentByTag(String tag)方法来获取指定的Fragment。
    2. 调用popBackStack()方法将Fragment从后台中弹出(模拟用户按下Back键)
    3. 调用addOnBackStackChangeListener()注册一个监听器,用于监听后台栈的变化。
  • Fragment事务

    如果需要添加,删除,替换Fragment,则需要借助于FragmentTransaction对象,FragmentTransaction代表Activity对Fragment执行多个改变

  • *

Fragment的生命周期

这里就不再手打赘述,直接从官网上复制最原始的解释给大家!多啰嗦一句,学习任何语言,官方文档一定要看。

The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:

  1. onAttach(Activity) :called once the fragment is associated with its activity.

  2. onCreate(Bundle): called to do initial creation of the fragment.

  3. onCreateView(LayoutInflater, ViewGroup, Bundle) :creates and returns the view hierarchy associated with the fragment.

  4. onActivityCreated(Bundle) :tells the fragment that its activity has completed its own Activity.onCreate().

  5. onViewStateRestored(Bundle) :tells the fragment that all of the saved state of its view hierarchy has been restored.

  6. onStart(): makes the fragment visible to the user (based on its containing activity being started).

  7. onResume(): makes the fragment begin interacting with the user (based on its containing activity being resumed).

As a fragment is no longer being used, it goes through a reverse series of callbacks:

  1. onPause(): fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.

  2. onStop(): fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.

  3. onDestroyView(): allows the fragment to clean up resources associated with its View.

  4. onDestroy(): called to do final cleanup of the fragment’s state.

  5. onDetach() :called immediately prior to the fragment no longer being associated with its activity.

创建Fragment

通常来说,创建Fragment只需要实现如下三个方法:  onCreat();  onCreatView();  onPause();按需求可重写其他方法。    

实例一:

MainActivity.java:用于对整个进程的控制

FoodContent:实体类

FoodListFragment:显示食品列表的Fragment

FoodDetailFragment:显示食品详细信息的Fragment

activity_main.xml:布局文件
……

MainActivity代码:

public class MainActivity extends AppCompatActivity implements FoodListFragment.Callbacks{    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    @Override    public void onItemSelected(Integer id) {        // 创建Bundle,准备向Fragment传入参数        Bundle arguments = new Bundle();        arguments.putInt(FoodDetailFragment.ITEM_ID, id);        // 创建FoodDetailFragment对象        FoodDetailFragment fragment = new FoodDetailFragment();        // 向Fragment传入参数        fragment.setArguments(arguments);        // 使用fragment替换book_detail_container容器当前显示的Fragment        getFragmentManager().beginTransaction()                .replace(R.id.food_detail_container, fragment)                .commit();    }}

FoodContent.java

public class FoodContent {    // 定义一个内部类,作为系统的业务对象    public static class Food    {        public Integer id;        public String name;        public String desc;        public Food(Integer id, String name, String desc)        {            this.id = id;            this.name = name;            this.desc = desc;        }        @Override        public String toString()        {            return name;        }    }    // 使用List集合记录系统所包含的Food对象    public static List<Food> ITEMS = new ArrayList<Food>();    // 使用Map集合记录系统所包含的Food对象    public static Map<Integer, Food> ITEM_MAP            = new HashMap<Integer, Food>();    static    {        // 使用静态初始化代码,将Food对象添加到List集合、Map集合中        addItem(new Food(1, "土豆"                , "马铃薯(学名:Solanum tuberosum),属茄科多年生草本植物,块茎可供食用,是全球第四大重要的粮食作物,仅次于小麦、稻谷和玉米。马铃薯又称地蛋、土豆 、洋山芋等,茄科植物的块茎。与小麦、稻谷、玉米、高粱并成为世界五大作物。"));        addItem(new Food(2, "紅薯"                , "[1]红薯(英文: sweet potato)原名番薯(学名:Ipomoea batatas (L.) Lam.),又名红芋、甘薯、蕃薯、大米、番芋、地瓜(北方)、红苕、线苕、白薯、金薯、甜薯、朱薯、枕薯、番葛、白芋、茴芋地瓜等。 "                ));        addItem(new Food(3, "黃瓜", "黄瓜,(学名Cucumis sativus Linn,英文名Cucumber),葫芦科黄瓜属植物。也称胡瓜、青瓜、刺瓜。果实颜色呈油绿或翠绿,表面有柔软的小刺。 中国各地普遍栽培,现广泛种植于温带和热带地区。"));        addItem(new Food(4, "茄子", "茄(学名:Solanum melongena)常称茄子,吴越人沿用宋代叫法称为落苏,广东人称为矮瓜,是茄科茄属一年生草本植物,热带为多年生。其结出的果实可食用,颜色多为紫色或紫黑色,也有淡绿色或白色品种,形状上也有圆形,椭圆,梨形等各种。茄子是一种典型的蔬菜,根据品种的不同,食用方法多样。"));        addItem(new Food(5, "萝卜", "萝卜(学名:Raphanus sativus)。别名莱菔、菜头,十字花科草本植物。萝卜的根部是最常见的蔬菜之一,但实际上整株植物都是可吃的。种子称为莱菔子,是常用的中药。"));        addItem(new Food(6, "韭菜", "山韭(拉丁学名:Allium senescens L.),是百合科葱属植物,产黑龙江、吉林、辽宁、河北、山西、内蒙古、甘肃(东部)、新疆(西北部)和河南、(西北部)。"));        addItem(new Food(7, "白菜", "白菜原产于我国北方,是十字花科芸薹属一年生、二年生草本植物。通常指大白菜;也包括小白菜以及由甘蓝的栽培变种结球甘蓝,即“圆白菜”或“洋白菜”。引种南方,南北各地均有栽培。"));        addItem(new Food(8, "冬瓜", "冬瓜,一年生草本植物,茎上有卷须,能爬蔓,叶子大,开黄花。果实球形或长圆柱形,表面有毛和白粉,皮深绿色,是普通蔬菜。皮和种子可入药。"));        addItem(new Food(9, "青菜", "青菜(Brassica chinensis var chinensis),中国东北称油菜,为一年生草本,芸苔属,颜色深绿,茎、叶用蔬菜。"));        addItem(new Food(10, "玉米", "玉米(拉丁学名:Zea mays L.)是禾本科玉米属一年生草本植物。别名:玉蜀黍、棒子、包谷、包米、玉茭、苞米、珍珠米、苞芦、大芦粟,潮汕话称幼米仁,粤语称为粟米,闽南语称作番麦。"));        addItem(new Food(11, "辣椒", "辣椒(学名:Capsicum annuum),又叫牛角椒、长辣椒、番椒、番姜、海椒、辣子、辣角、秦椒等,是一种茄科辣椒属植物。原产于中南美洲热带地区。"));    }    private static void addItem(Food Food)    {        ITEMS.add(Food);        ITEM_MAP.put(Food.id, Food);    }}

FoodListFragment.java

public class FoodListFragment extends ListFragment {    private Callbacks mCallbacks;    // 定义一个回调接口,该Fragment所在Activity需要实现该接口    // 该Fragment将通过该接口与它所在的Activity交互    public interface Callbacks    {        public void onItemSelected(Integer id);    }    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // 为该ListFragment设置Adapter        setListAdapter(new ArrayAdapter<FoodContent.Food>(getActivity(),                android.R.layout.simple_list_item_activated_1,                android.R.id.text1, FoodContent.ITEMS));    }    // 当该Fragment被添加、显示到Activity时,回调该方法    @Override    public void onAttach(Activity activity)    {        super.onAttach(activity);        // 如果Activity没有实现Callbacks接口,抛出异常        if (!(activity instanceof Callbacks))        {            throw new IllegalStateException(                    "FoodListFragment所在的Activity必须实现Callbacks接口!");        }        // 把该Activity当成Callbacks对象        mCallbacks = (Callbacks)activity;    }    // 当该Fragment从它所属的Activity中被删除时回调该方法    @Override    public void onDetach()    {        super.onDetach();        // 将mCallbacks赋为null。        mCallbacks = null;    }    // 当用户单击某列表项时激发该回调方法    @Override    public void onListItemClick(ListView listView            , View view, int position, long id)    {        super.onListItemClick(listView, view, position, id);        // 激发mCallbacks的onItemSelected方法        mCallbacks.onItemSelected(FoodContent                .ITEMS.get(position).id);    }    public void setActivateOnItemClick(boolean activateOnItemClick)    {        getListView().setChoiceMode(                activateOnItemClick ? ListView.CHOICE_MODE_SINGLE                        : ListView.CHOICE_MODE_NONE);    }}

FoodDetailFragment.java

public class FoodDetailFragment extends Fragment {    public static final String ITEM_ID = "item_id";    // 保存该Fragment显示的Food对象    FoodContent.Food food;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // 如果启动该Fragment时包含了ITEM_ID参数        if (getArguments().containsKey(ITEM_ID))        {            food = FoodContent.ITEM_MAP.get(getArguments()                    .getInt(ITEM_ID));        }    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        View ret = inflater.inflate(R.layout.fragment_food_detail, container, false);        if (food != null) {            // 让food_title文本框显示food对象的title属性            ((TextView) ret.findViewById(R.id.food_title))                    .setText(food.name);            // 让food_desc文本框显示food对象的desc属性            ((TextView) ret.findViewById(R.id.food_desc))                    .setText(food.desc);        }        return ret;    }}

main.xml代码:

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="horizontal"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.dejasen.fragmenttest.MainActivity">   <fragment       android:name="com.dejasen.fragmenttest.FoodListFragment"       android:id="@+id/food_list"       android:layout_weight="1"       android:layout_width="0dp"       android:layout_height="match_parent"/>    <FrameLayout        android:id="@+id/food_detail_container"        android:layout_weight="3"        android:layout_width="0dp"        android:layout_height="match_parent"/></LinearLayout>

实例二:

几个知识点:

  1. 用style写公用的属性
  2. radioButton和Fragment的连动
    MainActivity代码:
 @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,                WindowManager.LayoutParams.FLAG_FULLSCREEN);        setContentView(R.layout.activity_main);        RadioGroup group = (RadioGroup) findViewById(R.id.main_tab_bar);        if (group != null) {            group.setOnCheckedChangeListener(this);        }        mOneFragment = new OneFragment();        mTwoFragment = new TwoFragment();        mThreeFragment = new ThreeFragment();        mFourFragment = new FourFragment();        group.check(R.id.main_tab_item_send);    }    @Override    public void onCheckedChanged(RadioGroup group, int checkedId) {        FragmentManager fragmentManager = getSupportFragmentManager();        FragmentTransaction ft = fragmentManager.beginTransaction();        switch (checkedId){            case R.id.main_tab_item_send:                ft.replace(R.id.fragment_container,mOneFragment);                break;            case R.id.main_tab_item_cam:                ft.replace(R.id.fragment_container,mTwoFragment);                break;            case R.id.main_tab_item_tel:                ft.replace(R.id.fragment_container,mThreeFragment);                break;            case R.id.main_tab_item_dat:                ft.replace(R.id.fragment_container,mFourFragment);                break;        }        ft.commit();    }}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><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"    tools:context="com.jasen.fragmenthomework.MainActivity"    android:weightSum="1">    <!--<fragment        android:id="@+id/radioGroup"        class="com.jasen.fragmenthomework.Fragment.RadioFragment"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>-->    <FrameLayout        android:id="@+id/fragment_container"        android:layout_width="match_parent"        android:background="#cccccc"        android:layout_height="0dp"        android:layout_weight="1"        >    </FrameLayout>    <RadioGroup        android:id="@+id/main_tab_bar"        android:layout_width="match_parent"        android:layout_height="wrap_content"       android:layout_alignParentBottom="true"        android:orientation="horizontal"        >        <RadioButton            android:id="@+id/main_tab_item_send"            style="@style/rb_style"            android:drawableTop="@android:drawable/ic_menu_send"            android:text="发送"            />        <RadioButton            android:id="@+id/main_tab_item_cam"            style="@style/rb_style"            android:drawableTop="@android:drawable/ic_menu_camera"            android:text="相机"            />        <RadioButton            android:id="@+id/main_tab_item_tel"            style="@style/rb_style"            android:drawableTop="@android:drawable/ic_menu_call"            android:text="电话"            />        <RadioButton            android:id="@+id/main_tab_item_dat"            style="@style/rb_style"            android:drawableTop="@android:drawable/ic_menu_agenda"            android:text="日程"            />    </RadioGroup></LinearLayout>

styles.xml代码:

 <style name="rb_style">        <item name="android:gravity">center</item>        <item name="android:layout_weight">1</item>        <item name="android:layout_gravity">bottom</item>        <item name="android:layout_height">wrap_content</item>        <item name="android:layout_width">wrap_content</item>        <item name="android:button">@null</item>        <item name="android:textColor">@color/cb_color_sel</item>        <item name="android:drawableTint">@color/cb_color_sel</item>    </style>

选择器代码:

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_checked="true" android:color="#4b93f1"/>    <item android:color="#000"/></selector>
4 0
原创粉丝点击