作为一个Android开发人员,应该没有谁不知道Fragment!其重要性可想而知了!不多说,先上图
实例一(使用ListFragment和Fragment结合实现):
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的通讯如何处理!
Activity向Fragment传递数据:在Activity中创建Bundle数据包,并调用Fragment的setArgument(Bundle bundle)方法将Bundle数据传递给Fragment.
Fragment向Activity传递数据:Fragment中定义一个内部回调接口,再让包含该Fragment的Activity实现该回掉接口,这样就能将Fragment的数据传给Activity了!
如何将Fragment添加到Activity中:
在布局文件中使用<fragment…/>元素添加Fragment,<fragment…/>元素的android:name属性指定Fragment的实现类
在Java代码中通过FragmentTransaction对象的add()方法来添加Fragment.
Activity获取它包含的Fragment:用Fragment的getActivity();
Fragment获取它所在的Activity:调用关联的FragmentMangager的findFragmentById(int id)或者fingFragmentByTag(String tag)方法即可获取Fragment。
Fragment管理
FragmentManager可以实现以下几方面的功能:
使用 findFragmentById(int id)或fingFragmentByTag(String tag)方法来获取指定的Fragment。
调用popBackStack()方法将Fragment从后台中弹出(模拟用户按下Back键)
调用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>
作者:aserbao