1. 创建一个Fragment

一个空的 FrameLayout作为fragment的容器

article_view.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" /
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class ArticleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container, false);
}
}

2. 用XML将fragment添加到activity

news_articles.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<fragment android:name="com.example.android.fragments.ArticleFragment"
android:id="@+id/article_fragment"
android:layout_width="match_parent" android:layout_height="match_parent" />
</LinearLayout>

然后将这个布局文件用到你的activity中

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
}
}

注意:如果你用的是 v7 appcompat library,你的activity应该改为继承ActionBarActivity,ActionBarActivity是FragmentActivity
的一个子类

3. 在activity运行时添加添加fragment

activity 可以移除(在XML布局中用 <fragment>  定义的fragment)或者用另外一个(HeadlinesFragment为编写)来替换它

news_articles.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" /
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
//id 是 1 中的xml布局的id
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
ArticleFragment firstFragment = new ArticleFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
}

Fragment替换

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
//注意,后退键,调用destoryed;故 你必须在FragmentTransaction提交前调用addToBackStack()方法(放入栈中),调用的是stopped方法
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();

4 Fragments之间的交互

为了让fragment与activity交互, 你可以在Fragment 类中定义一个接口,并且在activity中实现这个接口。 Fragment在他们生命周期的onAttach()方法中捕获接口的实现,然后调用接口的方法来与Activity交互

public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}

Fragment就可以通过调用 OnHeadlineSelectedListener  接口实例的 mCallback  中的 onArticleSelected()  (也可以是
其它方法)方法与activity传递消息。

举个例子,在fragment中的下面的方法在用户点击列表条目时被调用,fragment 用回调接口来传递事件给父Activity.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onArticleSelected(position);

实现接口

public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
...
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
}
}

activity可以把从fragment回调方法中接收到的信息传递给新的Fragment

public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
...
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// Otherwise, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}

Fragemnt的更多相关文章

  1. 如何从fragment跳到activity再从activity返回(finish()方法返回)刷新fragemnt页面

    代码改变世界 如何从fragment跳到activity再从activity返回(finish()方法返回)刷新fragemnt页面 广播方法实现Fragment页面刷新 fragment中重写onA ...

  2. Fragemnt和TextView的交互(TextView在LinearLayout中)

    import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android ...

  3. TabActivity 、fragemnt+fragment 和 Fragment+Viewpager 优缺点

    1 TabActivity : 1 过时了 . 2 activity . 是作为android的四大组件...                   重量级的家伙   ViewGroup   : 特别麻 ...

  4. Android Fragment 剖析

    1.Fragment如何产生?2.什么是Fragment Android运行在各种各样的设备中,有小屏幕的手机,超大屏的平板甚至电视.针对屏幕尺寸的差距,很多情况下,都是先针对手机开发一套App,然后 ...

  5. Fragment的生命周期

    Fragment的生命周期: 1. onAttach():Fragment对象跟Activity关联时 2. onCreate():Fragment对象的初始创建时 3. onCreateView() ...

  6. 【Android自学日记】【转】Android Fragment 真正的完全解析(上)

    自从Fragment出现,曾经有段时间,感觉大家谈什么都能跟Fragment谈上关系,做什么都要问下Fragment能实现不~~~哈哈,是不是有点过~~~ 本篇博客力求为大家说明Fragment如何产 ...

  7. 对于Fragment的一些理解

    前言 Fragment想必大家不陌生吧,在日常开发中,对于Fragment的使用也很频繁,现在主流的APP中,基本的架构也都是一个主页,然后每个Tab项用Fragment做布局,不同选项做切换,使用起 ...

  8. Flipboard-BottomSheetlayout 源码分析

    BottomSheetLayout BottomSheet:Google在API 23中已经加入了这样的一个控件. BottomSheet介绍: BottomSheet是一个可以从底部飞入和飞出的An ...

  9. Android Fragment (二) 实例2

    由于看客的要求,我就把读者所要的写出来. 由于上一篇是每一个Fragment 实例了同一个layout.xml ,造成了读者的困惑,这篇我就让每一个Fragment 加载一个不同的layout.xml ...

随机推荐

  1. BZOJ 3436: 小K的农场 差分约束

    题目链接: http://www.lydsy.com/JudgeOnline/problem.php?id=3436 题解: 裸的差分约束: 1.a>=b+c  ->  b<=a-c ...

  2. The 2014 ACM-ICPC Asia Mudanjiang Regional First Round

    The Himalayas http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5341 签到 #include<cstdio& ...

  3. 并行编译加快 VS C++ 项目的编译速度

    最近编译的项目都比较大,话说自己的电脑配置还行,但编译所花的时间还是很长,遇到需要重新编译整个项目的时候真的有回宿舍睡一觉的冲动.昨天一不小心被我发现了一款软件Xoreax IncrediBuild ...

  4. QC缺陷管理操作-细说(转)

    一.缺陷常用字段说明 二.缺陷管理流程图 三.开发人员修改缺陷填写规范 四.项目经理决定延期修改缺陷 一.缺陷常用字段说明 1.摘要 对缺陷的简单描述.摘要包括该缺陷所属的模块名称-子模块名称,以及简 ...

  5. ${fn:length(worklicenseList)} #表示不在struts堆栈里,没有#表示从struts堆栈里取

    ${fn:length(worklicenseList)} #表示不在struts堆栈里,没有#表示从struts堆栈里取

  6. POJ 1915

    #include<iostream> #include<stdio.h> #define MAXN 350 #include"queue" using na ...

  7. 深入浅出ES6(六):解构 Destructuring

    作者 Jason Orendorff  github主页  https://github.com/jorendorff 什么是解构赋值? 解构赋值允许你使用类似数组或对象字面量的语法将数组和对象的属性 ...

  8. Java Excel

    http://www.cnblogs.com/mingforyou/archive/2013/08/26/3282922.html

  9. 取消 EditText 自动聚焦弹出输入法界面

    方法一(实测可行): 参考http://www.cnblogs.com/dream-cichan/p/aaaa.html 当我点击跳转至一个带有EditText的界面后,模拟器中的软键盘会自动弹出,严 ...

  10. python自定义函数在Python解释器中调用

    https://docs.python.org/2.7/tutorial/modules.html Modules If you quit from the Python interpreter an ...