Fragment为大量型号,尺寸,分辨率的设备提供了一种统一的UI优化方案。将Activity分解为多个Fragment,将极大地提高UI的灵活性,也更容易为一些新的设备配置带来更好的用户体验。

onCreate:

创建Fragment时系统调用它。

onCreateView:

首次绘制用户界面时系统调用这个方法。

onPause:

当用户离开Fragment时系统调用此方法。

onAttach:

当Fragment与Acitivity绑定时调用。

onActivityCreated:

当Fragment绑定的Activity调用onCreate方法时调用。

onDestroyView:

当与Fragment相关联的视图层次被删除时调用。

onDetach:

当Fragment与Acitivity解绑定时调用。

FragmentManager是每个Activity用来管理它所包含的Fragment。在Activity中切换Fragment时必须用到FragmentManager,Activity可以通过使用getFragmentManager方法来访问FragmentManager。

代码展示:

MainActivity.java

package com.example.demo15;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class MainActivity extends Activity implements OnCheckedChangeListener{

private RadioGroup group;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
group=(RadioGroup) findViewById(R.id.radiogroup);
group.setOnCheckedChangeListener(this);
}
@SuppressLint("NewApi") @Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.first:{
Intent intent=new Intent(this,MainActivity2.class);
startActivity(intent);
break;
}
case R.id.second:{
MyFragment2 fragment2=new MyFragment2();
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction beginTransaction=fragmentManager.beginTransaction();
beginTransaction.add(R.id.frame ,fragment2);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
break;
}
case R.id.thrid:{
Intent intent=new Intent(MainActivity.this,MainActivity3.class);
startActivity(intent);
break;
}
case R.id.fourth:{
Intent intent=new Intent(MainActivity.this,MainActivity4.class);
startActivity(intent);
break;
}
}
}
}

MainActivity2.java

package com.example.demo15;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity2 extends Activity{
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);

Button button=(Button) findViewById(R.id.button);
tv=(TextView) findViewById(R.id.text);
button.setText("刀冲");
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
tv.setText("TextView from 刀冲");
}
});
}
}

MainActivity3.java

package com.example.demo15;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity3 extends Activity{
private Button button;
private Fragment frag;
private boolean flag=true;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
init();
button=(Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {

@SuppressLint("NewApi") public void onClick(View v) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction beginTransaction=fragmentManager.beginTransaction();

if(flag){
MyFragment4 frag4=new MyFragment4();
beginTransaction.replace(R.id.layout,frag4);
}else{
MyFragment3 frag3=new MyFragment3();
beginTransaction.replace(R.id.layout,frag3);
}

beginTransaction.commit();
}
});
}

@SuppressLint("NewApi") private void init() {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction beginTransaction=fragmentManager.beginTransaction();
MyFragment3 frag3=new MyFragment3();
beginTransaction.add(R.id.layout,frag3);
beginTransaction.commit();
}
}

MainActivity4.java

package com.example.demo15;

import com.example.demo15.MyFragment5.MyListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity4 extends Activity implements MyListener{

private EditText editext;
private Button send;
@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main4);
editext=(EditText) findViewById(R.id.editText);
send=(Button) findViewById(R.id.send);

send.setOnClickListener(new OnClickListener() {

@SuppressLint("NewApi") @Override
public void onClick(View v) {
String text=editext.getText().toString();
MyFragment5 fragment5=new MyFragment5();
Bundle bundle=new Bundle();
bundle.putString("name",text);
fragment5.setArguments(bundle);
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction beginTransaction=fragmentManager.beginTransaction();

beginTransaction.add(R.id.layout,fragment5,"fragment5");
beginTransaction.commit();
Toast.makeText(MainActivity4.this,"fragment4"+text,Toast.LENGTH_SHORT).show();
}
});

FragmentManager fragmentManager=getFragmentManager();
Fragment findFragmentById=fragmentManager.findFragmentById(R.id.frag);
MyFragment frag=(MyFragment)findFragmentById;
frag.setAaa("frag-aaa-");
}

@Override
public void thank(String code) {
Toast.makeText(MainActivity4.this,"收到"+code+",客气了",Toast.LENGTH_SHORT).show();
}

}

MyFragment.java

package com.example.demo15;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi") public class MyFragment extends Fragment{

private String aaa;

public String getAaa() {
return aaa;
}

public void setAaa(String aaa) {
this.aaa = aaa;
}

@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//layout布局文件转换为View对象
//1.Fragment加载的布局文件 2.加载layout的父ViewGroup 3.false 不返回父ViewGroup
View view=inflater.inflate(R.layout.fragment,container,false);
TextView text=(TextView) view.findViewById(R.id.text);
Button button=(Button) view.findViewById(R.id.button);
text.setText("静态加载Fragment");
button.setText("done");
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
String value=getAaa();
Toast.makeText(getActivity(),"value="+value,Toast.LENGTH_SHORT).show();
}
});
return view;
}
}

MyFragment2.java

package com.example.demo15;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("NewApi") public class MyFragment2 extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment,container,false);
TextView text=(TextView) view.findViewById(R.id.text);
text.setText("动态传值");
return view;
}
}

MyFragment3.java

package com.example.demo15;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("NewApi") public class MyFragment3 extends Fragment{
private TextView tv;

@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment2,container,false);
TextView tv=(TextView) view.findViewById(R.id.text);
tv.setText("第一个Fragment");
Log.i("Main","Fragment1--onCreateView()");
return view;
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.i("Main","Fragment1--onAttach()");
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Main","Fragment1--onCreate()");
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("Main","Fragment1--onActivityCreated()");
}

@Override
public void onStart() {
super.onStart();
Log.i("Main","Fragment1--onStart()");
}

@Override
public void onResume() {
super.onResume();
Log.i("Main","Fragment1--onResume()");
}

@Override
public void onPause() {
super.onPause();
Log.i("Main","Fragment1--onPause()");
}

@Override
public void onStop() {
super.onStop();
Log.i("Main","Fragment1--onStop()");
}

@Override
public void onDestroyView() {
super.onDestroyView();
Log.i("Main","Fragment1--onDestroyView()");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.i("Main","Fragment1--onDestroy()");
}

@Override
public void onDetach() {
super.onDetach();
Log.i("Main","Fragment1--onDetach()");
}
}

MyFragment4.java

package com.example.demo15;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("NewApi") public class MyFragment4 extends Fragment{
private TextView tv;

@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment2,container,false);
TextView tv=(TextView) view.findViewById(R.id.text);
tv.setText("第二个Fragment");
Log.i("Main","Fragment2--onCreateView()");
return view;
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.i("Main","Fragment2--onAttach()");
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Main","Fragment2--onCreate()");
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("Main","Fragment2--onActivityCreated()");
}

@Override
public void onStart() {
super.onStart();
Log.i("Main","Fragment2--onStart()");
}

@Override
public void onResume() {
super.onResume();
Log.i("Main","Fragment2--onResume()");
}

@Override
public void onPause() {
super.onPause();
Log.i("Main","Fragment2--onPause()");
}

@Override
public void onStop() {
super.onStop();
Log.i("Main","Fragment2--onStop()");
}

@Override
public void onDestroyView() {
super.onDestroyView();
Log.i("Main","Fragment2--onDestroyView()");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.i("Main","Fragment2--onDestroy()");
}

@Override
public void onDetach() {
super.onDetach();
Log.i("Main","Fragment2--onDetach()");
}
}

MyFragment5.java

package com.example.demo15;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi") public class MyFragment5 extends Fragment{
private String code="Thank you,Activity";
public MyListener listener;
public interface MyListener{
public void thank(String code);
}

@Override
public void onAttach(Activity activity) {
listener=(MyListener) activity;
super.onAttach(activity);
}

@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment2,container,false);
TextView tv=(TextView) view.findViewById(R.id.text);
String text=getArguments().get("name")+"";
tv.setText(text);
Toast.makeText(getActivity(),"你好"+text,Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(),code,Toast.LENGTH_SHORT).show();
listener.thank(code);
return view;
}
}

布局文件:

activity_main.xml

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.demo15.MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container"
/>

fragment_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
/>

</RelativeLayout>

fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<Button
android:text="改变"
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

/>
</LinearLayout>

fragment2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

</LinearLayout>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
></LinearLayout>

<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:orientation="horizontal"
>

<RadioButton
android:id="@+id/first"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/radio_pressed"
android:button="@null"
android:drawableTop="@drawable/ic_launcher"
android:gravity="center_horizontal"
android:text="静态加载"
/>
<RadioButton
android:id="@+id/second"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/radio_pressed"
android:button="@null"
android:drawableTop="@drawable/ic_launcher"
android:gravity="center_horizontal"
android:text="动态加载"
/>
<RadioButton
android:id="@+id/thrid"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/radio_pressed"
android:button="@null"
android:drawableTop="@drawable/ic_launcher"
android:gravity="center_horizontal"
android:text="生命周期"
/>
<RadioButton
android:id="@+id/fourth"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/radio_pressed"
android:button="@null"
android:drawableTop="@drawable/ic_launcher"
android:gravity="center_horizontal"
android:text="传值通信"
/>

</RadioGroup>

</RelativeLayout>

main2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<fragment
android:id="@+id/fragment"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:name="com.example.demo15.MyFragment"
/>
</LinearLayout>

main3.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:text="切换Fragment"
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

</LinearLayout>

main4.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"
/>

<fragment
android:id="@+id/frag"
android:name="com.example.demo15.MyFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>

配置文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo15"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.demo15.MainActivity2"></activity>
<activity android:name="com.example.demo15.MainActivity3"></activity>
<activity android:name="com.example.demo15.MainActivity4"></activity>
</application>

</manifest>

Fragment学习笔记的更多相关文章

  1. Fragment 学习笔记(1)

    网上关于Fragment相关的博客资料很多,写关于这个知识笔记是加深记忆,大神略过: 0x01 了解Fragment 当然看官方文档(http://www.android-doc.com/refere ...

  2. Android Fragment学习笔记(二)----Fragment界面添加和管理

    Fragment界面添加 了解过fragment的生命周期等简单知识,于是去看官方文档来了解更多相关内容,要添加fragment到我们的UI界面中,给出了两种常用的方法,第一个是在activity的布 ...

  3. Android之Fragment学习笔记②(Fragment生命周期)

    一. Fragment生命周期图                                  二.Fragment生命周期方法介绍 Fragment的生命周期和activity生命周期很像,其生 ...

  4. Android之Fragment学习笔记①

    Android Fragment完全解析,关于碎片你所需知道的一切 一. 什么是FragmentFragment(碎片)就是小型的Activity,它是在Android3.0时出现的.Fragment ...

  5. viewpager+fragment学习笔记

    有暇,总结一下viewpager+fragment的使用. 先来看看效果图: 有三个标题,三个fragment,滑动时标题的颜色会随着变化. MainActivity.java public clas ...

  6. [android]p7-1 fragment学习笔记

    本文源自<android权威编程指南第3版>第7章UI fragment与fragment 第7章主要内容是实现一个记录不良行为的APP(部分实现),有列表,有具体的行为内容显示.第7章主 ...

  7. 【转】 Pro Android学习笔记(四二):Fragment(7):切换效果

    目录(?)[-] 利用setTransition 利用setCustomAnimations 通过ObjectAnimator自定义动态效果 程序代码的编写 利用fragment transactio ...

  8. 【转】 Pro Android学习笔记(四十):Fragment(5):适应不同屏幕或排版

    目录(?)[-] 设置横排和竖排的不同排版风格 改写代码 对于fragment,经常涉及不同屏幕尺寸和不同的排版风格.我们在基础小例子上做一下改动,在横排的时候,仍是现实左右两个fragment,在竖 ...

  9. 两千行PHP学习笔记

    亲们,如约而至的PHP笔记来啦~绝对干货! 以下为我以前学PHP时做的笔记,时不时的也会添加一些基础知识点进去,有时还翻出来查查. MySQL笔记:一千行MySQL学习笔记http://www.cnb ...

随机推荐

  1. 【iOS】XcodeColors插件与CocoaLumberjack工具

    工欲善其事必先利其器,好的开发者一定是懂得利用工具来提高自己的效率的,Xcode有很多第三方插件可以使用,最近发现一个可以给控制台着色的工具XcodeColors,结合CocoaLumberjack一 ...

  2. [Eclipse] - 解决导入flask模块出现的Unresolved Import flask问题

    http://www.cnblogs.com/mizhon/p/4242073.html [Eclipse] - 解决导入flask模块出现的Unresolved Import flask问题 最近想 ...

  3. ThinkPHP系的两个东东OneThink和ThinkCMF

    假设有这样一个命题:需要对一个已有系统进行移植,有没有什么系统是适合用来作为进行快速移植的基础的.能解决每个系统的基本问题,只需考虑相关业务逻辑问题. OneThink是TP团队官方出品. http: ...

  4. [转]PDO防注入原理分析以及使用PDO的注意事项

    原文:http://zhangxugg-163-com.iteye.com/blog/1835721 好文章不得不转. 我们都知道,只要合理正确使用PDO,可以基本上防止SQL注入的产生,本文主要回答 ...

  5. java中的代码块执行顺序

    /* 代码块:在Java中,使用{}括起来的代码被称为代码块. 根据其位置和声明的不同,可以分为 局部代码块:局部位置,用于限定变量的生命周期. 构造代码块:在类中的成员位置,用{}括起来的代码.每次 ...

  6. 从自签名证书导出pfx和cer证书

    完整代码: public sealed class DataCertificate { #region 生成证书 /// <summary> /// 根据指定的证书名和makecert全路 ...

  7. SQL数据库基础(三)

    认识数据库备份和事务日志备份 数据库备份与日志备份是数据库维护的日常工作,备份的目的是在于当数据库出现故障或者遭到破坏时可以根据备份的数据库及事务日志文件还原到最近的时间点将损失降到最低点. 数据库备 ...

  8. [HTML5] 飞龙天惊-HTML5学习系列

    飞龙天惊 cnblog URL:http://www.cnblogs.com/fly_dragon/ Html5 学习系列(一)认识HTML5 http://www.cnblogs.com/fly_d ...

  9. Linux学习笔记(整理记录)

    1.安装 (1):安装网址:http://www.jb51.net/os/78318.html 2.鸟哥的Linux命令学习 (1):显示系统目前所支持的语言:echo $LANG (2):修改语言成 ...

  10. 初学Node(二)package.json文件

    package.json简介 package.json在Node项目中用于描述项目的一些基本信息,以及依赖的配置,一般每一个Node项目的根目录下都有一个package.json文件. 在项目的根目录 ...