Fragment

onCreateView()方法

Fragment第一次绘制它的用户界面的时候,系统会调用此方法,为了

绘制Fragment的UI,此方法必须返回一个View,如果不显示UI,返回null即可

Fragment加载方式

(1)静态加载

(2)动态加载

先讲一下静态加载

在Activity的layout文件中声明Fragment,需要特别注意的是<fragment>中的android:name属性

指定了在layout中实例化的Fragment类


标识Fragment的方法:

android:id属性提供一个唯一ID

android:tag属性提供一个唯一字符串

在MainActivity布局文件中静态加载:

<?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_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="com.example.android_fragment.MyFragment"
        />

</LinearLayout>

MyFragment的onCreateView方法

下面是在MyFragment中获取MyFragment布局文件中的控件

@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//layout布局文件转换成View对象
		/**参数含义
		 * resource:Fragment需要加载的布局文件
		 * root:加载layout的父ViewGroup
		 * attactToRoot: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("获取内容");
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String value = getAaa();
				Toast.makeText(getActivity(), "value="+value, Toast.LENGTH_SHORT).show();
			}
		});
		return view;
	}
在MainActivity中也可以获取MyFragment中布局文件的控件
@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		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) {
				// TODO Auto-generated method stub
				tv.setText("TextView改变了");
			}
		});
		
	}

通过这个案例告诉大家

当在一个Activity的布局文件中,我们通过静态加载的方式把一个Fragment加载到Activity的布局文件中,那么Fragment中的布局文件(包括里面的控件)

对于Activity是共享的,在Activity中可以通过findviewbyId找到

下面学习动态加载Fragment

动态加载就是在代码中将Fragment添加到一个Activity layout中,并在代码中控制Fragment

动态加载需要处理Fragment事务

:根据用户的交互情况,对Fragment进行添加,移除,替换,以及执行其他动作,提交给Activity的每一套变化被称作一个事务。

FragmentManager fragmentManager = getFragmentManager();

FragmentTransaction beginTransaction = fragmentManager.beginTransaction();

每一个事务都是同时执行一套变化,可以在一个事务中设置你所想执行的变化,包括add(),

remove(),replace(),然后提交给Activity,必须调用commit()方法


如果允许用户通过按下BACK按键返回前一个Fragment状态,可以在调用commit()之前加入addToBackStack()方法

下面是把fragment2加载到id为frame LinearLayout中

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

//动态加载Fragment,动态加载需要开启事务
			MyFragment2 fragment2=new MyFragment2();
			//获取Fragment的管理 者
			FragmentManager fragmentManager = getFragmentManager();
			//获取开启事务的对象
			FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
			//第一个参数是说要把fragment2加载到哪个布局就把哪个布局的Id填进来
			beginTransaction.add(R.id.frame, fragment2);
			beginTransaction.addToBackStack(null);
			beginTransaction.commit();//提交事务

关于Fragment的生命周期这里暂时先不讲

Fragment与Activity通信

Activity-》Fragment:在Activity中创建Bundle数据包,并调用Fragment的

setArguments(Bundle bundle)方法,然后在Fragment中用getArguments()方法获取数据包


Fragment-》Activity:需要在Fragment中定义一个内部回调接口,

再让包含该Fragment的Activity实现该回调接口。这样Fragment可以

调用该回调方法将数据传递给Activity

1Activity向Fragment传递数据

Activity发送数据

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");//添加并设置Fragment的Tag
				beginTransaction.commit();
				Toast.makeText(MainActivity4.this, "向Fragment发送数据" + text,
						Toast.LENGTH_SHORT).show();

Fragment接受数据

String text=getArguments().get("name")+"";
        tv.setText(text);
		Toast.makeText(getActivity(), "已成功接收到"+text, Toast.LENGTH_SHORT).show();
2.Fragment向Activity传值,使用接口回调

例如向Activity传递一个字符串

private String code="Thank you,Activity!";
	
	public MyListener listener;
	public interface MyListener
	{
		public void thank(String code);
	}

然后重写方法onAttach,当Fragment被添加到Activity中时会被调用,在该方法中获得宿主Activity,

@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub	
		listener=(MyListener) activity;
		super.onAttach(activity);
	}

然后利用接口回调机制传值

@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment2, container, false);
		Toast.makeText(getActivity(), "向Activity发送"+code, Toast.LENGTH_SHORT).show();
		listener.thank(code);
		return view;
	}

让宿主Activity实现定义的接口

并实现接口中的方法

@Override
	public void thank(String code) {
		// TODO Auto-generated method stub
		Toast.makeText(MainActivity4.this, "已成功接收到" + code + ",客气了!",
				Toast.LENGTH_SHORT).show();
	}

上面是动态加载Fragment实现传值通信

下面讲解静态加载的Fragment怎么传值


宿主Activity的布局文件

<?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.android_fragment.MyFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

静态加载的MyFragment,实现与宿主Activity的传递数据,需要在在Fragment中添加数据的set,get方法

package com.example.android_fragment;

import android.app.Fragment;
import android.os.Bundle;
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;

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, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//layout布局文件转换成View对象
		/**
		 * resource:Fragment需要加载的布局文件
		 * root:加载layout的父ViewGroup
		 * attactToRoot: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("获取内容");
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String value = getAaa();
				Toast.makeText(getActivity(), "value="+value, Toast.LENGTH_SHORT).show();
			}
		});
		return view;
	}

}

然后在宿主Activity中通过下面的方法获取在布局文件中静态加载的Fragment,

这样就可调用Fragment中的方法进行数据传递了

FragmentManager fragmentManager = getFragmentManager();
		Fragment findFragmentById = fragmentManager.findFragmentById(R.id.frag);
        MyFragment frag=(MyFragment) findFragmentById;
        frag.setAaa("fragment静态传值");


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值