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. matlab和本机MySQL链接

    1.安装好 ***matlab*** 和 ***mysql***: 2.[下载](http://dev.mysql.com/downloads/connector/j/#downloads) mysq ...

  2. 3640: JC的小苹果 - BZOJ

    让我们继续JC和DZY的故事.“你是我的小丫小苹果,怎么爱你都不嫌多!”“点亮我生命的火,火火火火火!”话说JC历经艰辛来到了城市B,但是由于他的疏忽DZY偷走了他的小苹果!没有小苹果怎么听歌!他发现 ...

  3. Codeforces Round #343 (Div. 2) C. Famil Door and Brackets

    题目链接: http://codeforces.com/contest/629/problem/C 题意: 长度为n的括号,已经知道的部分的长度为m,现在其前面和后面补充‘(',或')',使得其长度为 ...

  4. spring配置事务

    一.配置JDBC事务处理机制 <!-- 配置Hibernate事务处理 --> <bean id="transactionManager" class=" ...

  5. java.lang.IllegalArgumentException: Requested window android.os.BinderProxy@450b2f48 异常处理

    晕死的错误,改了半天也没想到是这样的原因,基础正要呀... 先看一下警告信息: 07-07 08:32:19.540: WARN/WindowManager(74): Failed looking u ...

  6. Openstack Quantum project 更名为 Neuron

    因为与磁带备份厂商Quantum商标冲突: The OpenStack Foundation has changed the name of its networking project from Q ...

  7. [转载]Java学习这七年

    从2005那会做自动化测试开始接触Java开始,至今近7年.今天正好项目结束,趁机整理下思路,确定后续方向. 前三个年头基本上集中于Java基础的学习,包括设计模式,从完全不懂,到看的懂但似乎又不懂, ...

  8. sql over()---转载

    1.使用over子句与rows_number()以及聚合函数进行使用,可以进行编号以及各种操作.而且利用over子句的分组效率比group by子句的效率更高. 2.在订单表(order)中统计中,生 ...

  9. hdu 2112 HDU Today (最短路,字符处理)

    题目 题目很简单,只是多了对地名转化为数字的处理,好吧,这我也是参考网上的处理办法,不过大多数的人采用map来处理 注意初始化注意范围,不然会wa!!!(这是我当时wa的原因org) 大家容易忽视的地 ...

  10. hdu 1524 A Chess Game 博弈论

    SG函数!! 代码如下: #include<stdio.h> #include<cstring> #define I(x) scanf("%d",& ...