Fragment在Android中的使用

来源:互联网 发布:三级网络技术题库软件 编辑:程序博客网 时间:2024/05/29 14:59

应用场景:

众所了解Android上的界面展示都是通过Activity实现的,但是Activity也有它的局限性,同样的界面在手机上显示可能很好看,在平板上就未必了。为了让界面可以在平板上更好地展示,Android在3.0版本引入了Fragment(碎片)功能,它非常类似于Activity,可以像Activity一样包含布局。Fragment通常是嵌套在Activity中使用的。首先需要注意,Fragment是在3.0版本引入的,如果你使用的是3.0之前的系统,需要先导入android-support-v4的jar包才能使用Fragment功能。

知识点介绍:

一、如何创建Fragment。
首先需要创建继承Fragment的子类,Fragment类的代码看起来很像Activity。它与Activity一样都有回调函数,例如onCreate(),onStart(),onPause(),和onStop()。事实上,如果你正在将一个现成的Android应用转而使用Fragment来实现,可以简单的将代码从Activity的回调函数移植到各自的Fragment的回调函数中,简单而可行。
Fragment的生命周期方法主要包括如下:

1、onAttach

2、onCreate

3、onCreateView

4、onActivityCreated

5、onDestroyView

6、onDestroy

7、onPause

 

view sourceprint?
01.public class TestFragment extends Fragment {
02./**当Fragment已经跟Activity关联上的时候,这个回调被调用。Activity会作为onAttach()回调方法的参数来传递*/
03.@Override
04.public void onAttach(Activity activity) {
05.super.onAttach(activity);
06.}
07. 
08./**当创建Fragment时,系统调用该方法
09.在实现代码中, 应当初始化想要在Fragment中保持的必要组件, 当Fragment被暂停或者停止后可以再次恢复。*/
10.@Override
11.public void onCreate(Bundle savedInstanceState) {
12.super.onCreate(savedInstanceState);
13.}
14. 
15./**Fragment第一次绘制它的用户界面的时候, 系统会调用此方法。
16.为了绘制Fragment的UI, 此方法必须返回一个View, 这个view是你的Fragment布局的根view。*/
17.@Override
18.public View onCreateView(LayoutInflater inflater, ViewGroup container,
19.Bundle savedInstanceState) {
20.// R.layout.activity_main 自定义的布局文件
21.View view = inflater.inflate(R.layout.activity_main, null);
22.return view;
23.//      return super.onCreateView(inflater, container, savedInstanceState);
24.}
25. 
26./**当Activity的onCreate()方法执行完之后,调用这个回调方法。*/
27.@Override
28.public void onActivityCreated(Bundle savedInstanceState) {
29.super.onActivityCreated(savedInstanceState);
30.}
31. 
32./**当跟Fragment关联的视图层正在被删除时,调用这个回调方法。*/
33.@Override
34.public void onDestroyView() {
35.super.onDestroyView();
36.}
37. 
38./**当从Activity中解除Fragment的关联时,调用这个回调方法。*/
39.@Override
40.public void onDestroy() {
41.super.onDestroy();
42.}
43. 
44./*================================================================*/
45./**用户将要离开Fragment时,系统调用这个方法作为第一个指示(然而它不总是意味着Fragment将被销毁。)
46.在当前用户会话结束之前,通常应当在这里提交任何应该持久化的变化(因为用户有可能不会返回)。*/
47.@Override
48.public void onPause() {
49.super.onPause();
50.}
51.}

二、如何将Fragment添加到Activity。
此部分可以参看http://blog.csdn.net/t12x3456/article/details/8104574 这篇文章,博主写的很详尽。本文主要侧重于【在代码中添加Fragment到ViewGroup】的方式。
使用此方法需要了解一下以下三个类对象:
android.support.v4.app.FragmentActivity
android.support.v4.app.FragmentManager
android.support.v4.app.FragmentTransaction
首先我们使用的Activity需要继承(extends)FramentActivtiy。
public class MainActivity extends FragmentActivity然后通过获取FragmentTransaction 对象得到FragmentTransaction来完成Fragment的事务(比如添加,删除,替换等)操作,最后提交事务。

 

 

view sourceprint?
1.FragmentManager fragmentManager = getSupportFragmentManager();
2.FragmentTransaction transaction = fragmentManager.beginTransaction();
3.ExampleFragment fragment = new ExampleFragment();
4.transaction.add(R.id.main_frameLayout, fragment);
5.transaction.commit();

 

使用方式:

第一步:新建项目FragmentStudy,AndroidManifest.xml如下:

 

 

view sourceprint?
01.<?xml version="1.0" encoding="utf-8"?>
02.<manifest xmlns:android="http://schemas.android.com/apk/res/android"
03.package="com.example.fragmentstudy"
04.android:versionCode="1"
05.android:versionName="1.0" >
06.<uses-sdk
07.android:minSdkVersion="8"
08.android:targetSdkVersion="17" />
09.<application
10.android:allowBackup="true"
11.android:icon="@drawable/ic_launcher"
12.android:label="@string/app_name"
13.android:theme="@android:style/Theme.Black.NoTitleBar" >
14.<activity
15.android:name="com.example.fragmentstudy.MainActivity"
16.android:label="@string/app_name" >
17.<intent-filter>
18.<action android:name="android.intent.action.MAIN" />
19.<category android:name="android.intent.category.LAUNCHER" />
20.</intent-filter>
21.</activity>
22.</application>
23.</manifest>

第二步:创建ExampleFragment(Fragment的子类)与ExampleFragment相应的布局文件layout_fragment_example.xml。
【layout_fragment_example.xml】

 

 

view sourceprint?
01.<?xml version="1.0" encoding="utf-8"?>
02.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03.android:layout_width="match_parent"
04.android:layout_height="match_parent"
05.android:orientation="vertical" >
06.<TextView android:layout_height="wrap_content"
07.android:layout_width="match_parent"
08.android:text="ExampleFragment"
09.android:gravity="center"
10.android:id="@+id/fragment_textView"
11.android:textColor="@android:color/black"/>
12.</LinearLayout>

【ExampleFragment.java】

 

 

view sourceprint?
01.import java.util.Date;
02. 
03.import android.annotation.SuppressLint;
04.import android.os.Bundle;
05.import android.support.v4.app.Fragment;
06.import android.view.LayoutInflater;
07.import android.view.View;
08.import android.view.ViewGroup;
09.import android.widget.TextView;
10. 
11.@SuppressLint("ValidFragment")
12.public class ExampleFragment extends Fragment{
13. 
14.private String title = "";
15.public ExampleFragment(String title) {
16.super();
17.this.title = title;
18.}
19.@Override
20.public View onCreateView(LayoutInflater inflater, ViewGroup container,
21.Bundle savedInstanceState) {
22. 
23.View view = inflater.inflate(R.layout.layout_fragment_example, null);
24.TextView textView = (TextView) view.findViewById(R.id.fragment_textView);
25.textView.setText(textView.getText().toString()+"
26."+title+"
27."+new Date().getTime());
28.//      return super.onCreateView(inflater, container, savedInstanceState);
29.return view;
30.}
31.}
第三步:编写activity_main.xml主布局文件与MainActivity.java。
【activity_main.xml】

 

 

view sourceprint?
01.<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
02.xmlns:tools="http://schemas.android.com/tools"
03.android:layout_width="match_parent"
04.android:background="@android:color/white"
05.android:layout_height="match_parent"
06.tools:context=".MainActivity" >
07.<FrameLayout android:layout_height="match_parent"
08.android:layout_width="match_parent"
09.android:id="@+id/main_frameLayout">
10.</FrameLayout>
11.<LinearLayout android:layout_height="wrap_content"
12.android:layout_width="match_parent"
13.android:layout_alignParentBottom="true"
14.android:orientation="vertical">
15.<GridView android:layout_height="wrap_content"
16.android:layout_width="match_parent"
17.android:columnWidth="50dp"
18.android:horizontalSpacing="10dp"
19.android:id="@+id/main_gridView"
20.android:numColumns="3">
21.</GridView>
22.</LinearLayout>
23.</RelativeLayout>
【MainActivity.java】

 

 

view sourceprint?
01.import java.util.ArrayList;
02.import java.util.List;
03. 
04.import com.example.fragmentstudy.adapter.GridAdapter;
05.import com.example.fragmentstudy.domain.GridInfo;
06. 
07.import android.os.Bundle;
08.import android.graphics.Color;
09.import android.graphics.drawable.ColorDrawable;
10.import android.support.v4.app.FragmentActivity;
11.import android.support.v4.app.FragmentManager;
12.import android.support.v4.app.FragmentTransaction;
13.import android.view.Menu;
14.import android.view.View;
15.import android.widget.AdapterView;
16.import android.widget.AdapterView.OnItemClickListener;
17.import android.widget.GridView;
18. 
19.public class MainActivity extends FragmentActivity {
20. 
21.private GridView gridView;
22.private List<GridInfo> gridInfos = new ArrayList<GridInfo>();
23. 
24.@Override
25.protected void onCreate(Bundle savedInstanceState) {
26.super.onCreate(savedInstanceState);
27.setContentView(R.layout.activity_main);
28.initViews();
29.}
30. 
31.private void initViews() {
32.gridView = (GridView) findViewById(R.id.main_gridView);
33.GridAdapter gridAdapter = new GridAdapter(MainActivity.this);
34.getGridOnfoList();
35.gridAdapter.setList(gridInfos);
36.gridView.setAdapter(gridAdapter);
37.gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
38.FragmentManager fragmentManager = getSupportFragmentManager();
39.FragmentTransaction transaction = fragmentManager.beginTransaction();
40.ExampleFragment fragment = new ExampleFragment("主功能页面");
41.transaction.add(R.id.main_frameLayout, fragment);
42.transaction.commit();
43.gridView.setOnItemClickListener(new OnItemClickListener() {
44. 
45.@Override
46.public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
47.long arg3) {
48.FragmentManager fragmentManager = getSupportFragmentManager();
49.FragmentTransaction transaction = fragmentManager.beginTransaction();
50.//通过anim xml 配置Fragment切换效果  new / old
51.//上出下进
52.transaction.setCustomAnimations(R.anim.push_up_in, R.anim.push_up_out);
53.GridInfo info = gridInfos.get(arg2);
54.ExampleFragment fragment = new ExampleFragment(info.getName());
55.transaction.replace(R.id.main_frameLayout,fragment);
56.//              transaction.addToBackStack(null);  //提供返回上一页面的功能
57.transaction.commit();
58.}
59.});
60.}
61. 
62.private void getGridOnfoList() {
63.for(int i=0;i<6;i++){
64.GridInfo gridInfo = new GridInfo("测试"+i, R.drawable.ic_launcher+"");
65.gridInfos.add(gridInfo);
66.}
67.}
68.}

第四步:本演示项目的主要代码如上,一下为辅助的GirdView菜单效果的相关.java文件与.xml文件。

【GridInfo.java】

 

 

view sourceprint?
01.public class GridInfo {
02.private String name;
03.private String appImage;
04.public GridInfo(String name, String appImage) {
05.super();
06.this.name = name;
07.this.appImage = appImage;
08.}
09.public String getAppImage() {
10.return appImage;
11.}
12.public String getName() {
13.return name;
14.}
15.public void setName(String name) {
16.this.name = name;
17.}
18.}

【GirdAdapter.java】

 

 

view sourceprint?
01.import java.util.List;
02. 
03.import com.example.fragmentstudy.R;
04.import com.example.fragmentstudy.domain.GridInfo;
05. 
06.import android.content.Context;
07.import android.graphics.Color;
08.import android.view.Gravity;
09.import android.view.LayoutInflater;
10.import android.view.View;
11.import android.view.ViewGroup;
12.import android.widget.BaseAdapter;
13.import android.widget.ImageView;
14.import android.widget.TextView;
15. 
16.public class GridAdapter extends BaseAdapter {
17.private class GridHolder {
18.ImageView appImage;
19.TextView appName;
20.}
21.private Context context;
22.private List<GridInfo> list;
23.private LayoutInflater mInflater;
24.public GridAdapter(Context c) {
25.super();
26.this.context = c;
27.}
28.public void setList(List<GridInfo> list) { 
29.this.list = list; 
30.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
31.}
32.@Override
33.public int getCount() {
34.return list.size();
35.}
36.@Override
37.public Object getItem(int position) {
38.return list.get(position);
39.}
40.@Override
41.public long getItemId(int position) {
42.return position;
43.}
44.@Override
45.public View getView(int position, View convertView, ViewGroup parent) {
46.GridHolder holder; 
47.if (convertView == null) {    
48.convertView = mInflater.inflate(R.layout.grid_item, null);    
49.holder = new GridHolder(); 
50.holder.appImage = (ImageView)convertView.findViewById(R.id.itemImage); 
51.holder.appName = (TextView)convertView.findViewById(R.id.itemText); 
52.convertView.setTag(holder);    
53.}else
54.holder = (GridHolder) convertView.getTag();    
55.
56.GridInfo info = list.get(position); 
57.if (info != null) {    
58.holder.appName.setText(info.getName()); 
59.int colorInt = Color.parseColor("#CCFF66");
60.if(position%6==1){
61.colorInt = Color.parseColor("#336699");
62.else if (position%6==2) {
63.colorInt = Color.parseColor("#663366");
64.}else if (position%6==3) {
65.colorInt = Color.parseColor("#ABCDEF");
66.}else if (position%6==4) {
67.colorInt = Color.parseColor("#669933");
68.}else if (position%6==5) {
69.colorInt = Color.parseColor("#CC3399");
70.}      
71.holder.appImage.setBackgroundColor(colorInt);
72.holder.appName.setTextColor(Color.BLACK);
73.holder.appName.setGravity(Gravity.CENTER);
74.
75.return convertView; 
76.}
77.}

【grid_item.xml】

 

 

view sourceprint?
01.<?xml version="1.0" encoding="utf-8"?>
02.<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
03.android:layout_width="match_parent"
04.android:layout_height="wrap_content"
05.android:paddingBottom="4dip" >
06.<ImageView
07.android:id="@+id/itemImage"
08.android:layout_width="60dp"
09.android:layout_height="60dp"
10.android:layout_centerHorizontal="true" >
11.</ImageView>
12.<TextView
13.android:id="@+id/itemText"
14.android:layout_width="wrap_content"
15.android:layout_height="wrap_content"
16.android:layout_below="@id/itemImage"
17.android:layout_centerHorizontal="true"
18.android:layout_marginTop="4dp"
19.android:gravity="center"
20.android:text="TextView01"
21.android:textColor="@android:color/black"
22.android:textSize="10dp" >
23.</TextView>
24.</RelativeLayout>

除此之外还需要两个动画效果文件res/anim下的push_up_in.xml、push_up_out.xml。
【push_up_in.xml】

 

 

view sourceprint?
01.<?xml version="1.0" encoding="utf-8"?>    
02.<!-- 上滑切入 -->
03.<set xmlns:android="http://schemas.android.com/apk/res/android"  
04.android:interpolator="@android:anim/decelerate_interpolator">    
05.<translate
06.android:fromXDelta="0%p" android:toXDelta="0%p"
07.android:fromYDelta="100%p" android:toYDelta="0%p"
08.android:duration="1000" />
09.</set>
【push_up_out.xml】

 

 

view sourceprint?
01.<?xml version="1.0" encoding="utf-8"?>    
02.<!-- 上滑切出 -->
03.<set xmlns:android="http://schemas.android.com/apk/res/android"  
04.android:interpolator="@android:anim/decelerate_interpolator">        
05.<translate
06.android:fromXDelta="0%p" android:toXDelta="0%p"
07.android:fromYDelta="0%p" android:toYDelta="-100%p"
08.android:duration="1000" />
09.</set>

 

页面效果:

\


文章转自编程大巴:http://www.it165.net/pro/html/201406/15070.html

 

0 0
原创粉丝点击