Fragemnt
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的更多相关文章
- 如何从fragment跳到activity再从activity返回(finish()方法返回)刷新fragemnt页面
代码改变世界 如何从fragment跳到activity再从activity返回(finish()方法返回)刷新fragemnt页面 广播方法实现Fragment页面刷新 fragment中重写onA ...
- Fragemnt和TextView的交互(TextView在LinearLayout中)
import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android ...
- TabActivity 、fragemnt+fragment 和 Fragment+Viewpager 优缺点
1 TabActivity : 1 过时了 . 2 activity . 是作为android的四大组件... 重量级的家伙 ViewGroup : 特别麻 ...
- Android Fragment 剖析
1.Fragment如何产生?2.什么是Fragment Android运行在各种各样的设备中,有小屏幕的手机,超大屏的平板甚至电视.针对屏幕尺寸的差距,很多情况下,都是先针对手机开发一套App,然后 ...
- Fragment的生命周期
Fragment的生命周期: 1. onAttach():Fragment对象跟Activity关联时 2. onCreate():Fragment对象的初始创建时 3. onCreateView() ...
- 【Android自学日记】【转】Android Fragment 真正的完全解析(上)
自从Fragment出现,曾经有段时间,感觉大家谈什么都能跟Fragment谈上关系,做什么都要问下Fragment能实现不~~~哈哈,是不是有点过~~~ 本篇博客力求为大家说明Fragment如何产 ...
- 对于Fragment的一些理解
前言 Fragment想必大家不陌生吧,在日常开发中,对于Fragment的使用也很频繁,现在主流的APP中,基本的架构也都是一个主页,然后每个Tab项用Fragment做布局,不同选项做切换,使用起 ...
- Flipboard-BottomSheetlayout 源码分析
BottomSheetLayout BottomSheet:Google在API 23中已经加入了这样的一个控件. BottomSheet介绍: BottomSheet是一个可以从底部飞入和飞出的An ...
- Android Fragment (二) 实例2
由于看客的要求,我就把读者所要的写出来. 由于上一篇是每一个Fragment 实例了同一个layout.xml ,造成了读者的困惑,这篇我就让每一个Fragment 加载一个不同的layout.xml ...
随机推荐
- vs2008中使用正则删除空行
起因 今天下了段代码复制到VS2008中想好好学习下,结果发现每隔一行都有一行空白行(如下图),如果只有几行么手动删下就好了,但是这边估计有几百行,我也不知道VS2008有没有什么支持快速删除空白行的 ...
- 2565: 最长双回文串 - BZOJ
Description 顺序和逆序读起来完全一样的串叫做回文串.比如acbca是回文串,而abc不是(abc的顺序为“abc”,逆序为“cba”,不相同). 输入长度为n的串S,求S的最长双回文子串T ...
- Codeforces Round #238 (Div. 2) D. Toy Sum 暴搜
题目链接: 题目 D. Toy Sum time limit per test:1 second memory limit per test:256 megabytes 问题描述 Little Chr ...
- 剑指offer--面试题19
题目:求二叉树镜像 根据作者思路,自己所写代码如下: void BinaryTreeMirror(BinaryTreeNode* pRoot) { if(pRoot == NULL) return; ...
- springMVC+ibatis数据持久化入门级学习例子
1.web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=" ...
- 【C++基础】指针好难啊,一点点啃——基本概念
指针保存的是另一个对象的地址(概念真的很重要!!) ; int *ptr = &a;//*定义一个指向int类型的指针ptr, &a取变量a的地址 引用是对象的别名,多用于函数形参,引 ...
- 【redis】03list类型
list类型 redis的list类型是一个链表结构,他的主要功能是push.pop.获取一个范围的所有值等等一些操作, 咱们push什么意思,push是不是相当于咱们php里面的array_push ...
- SPOJ CNTPRIME 13015 Counting Primes (水题,区间更新,求区间的素数个数)
题目连接:http://www.spoj.com/problems/CNTPRIME/ #include <iostream> #include <stdio.h> #incl ...
- Network Saboteur(Rand版)
poj2531:http://poj.org/problem?id=2531 题意:给你一个图,图中点之间会有边权,现在问题是把图分成两部分,使得两部分之间边权之和最大.题解:随机算法 #includ ...
- POJ 1850
#include <iostream> #include <string> using namespace std; int fac(int num); int C(int n ...