android中fragment简单使用以及fragment之间数据交互

1.fragment产生的原因:

Fragment的出现解决了小屏幕的手机,超大屏的平板甚至电视兼容性,不用再针对不同设备再调试布局了,

对android开发者是一大福利啊;

2.fragment的生命周期:

Fragment必须是依存与Activity而存在的,因此Activity的生命周期会直接影响到Fragment的生命周期。

onAttach(Activity)        //当Fragment与Activity发生关联时调用。
onCreateView(LayoutInflater, ViewGroup,Bundle)//创建该Fragment的视图
onActivityCreated(Bundle)//当Activity的onCreate方法返回时调用
onDestoryView()//与onCreateView想对应,当该Fragment的视图被移除时调用
onDetach() //与onAttach相对应,当Fragment与Activity关联被取消时调用
注意:除了onCreateView,其他的所有方法如果你重写了,必须调用父类对于该方法的实现

3.fragment如何使用:

本例子中有三个类MainActivity,ReceiveDataFragment,SendDataFragment.其中 SendDataFragment使用了回调函数,是为了让fragment可以访问activity的例子。

ReceiveDataFragment使用了getArguments为了适配多种设备,注释中有详细的说明.


onCreate()创建了两个fragment通过FragmentManager放入activity中,而onArticleSelected方法是留给SendDataFragment调用,通过回调提供了SendDataFragment访问

activity的入口,而activity访问fragment对象,可以在Fragment写一个动态方法,供activity使用.

public class MainActivity extends Activity implements
		SendDataFragment.OnHeadlineSelectedListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		//FragmentManager能够实现管理activity中fragment.通过调用activity的getFragmentManager()取得它的实例。
		FragmentManager fragmentManager = getFragmentManager(); 
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		
		//向actvity添加receiveFragment
		ReceiveDataFragment receiveFragment = new ReceiveDataFragment();
		Bundle args = new Bundle();
		args.putInt(ReceiveDataFragment.ARG_POSITION, 88);
		/*
		 * Activity重新创建时,会重新构建它所管理的Fragment,原先的Fragment的字段 将会全部丢失,但是通过
		 * Fragment.setArguments(Bundle bundle)方法设 置的bundle会保留下来。所以尽量使用
		 * Fragment.setArguments(Bundle bundle)方式来传递参数
		 */
		receiveFragment.setArguments(args);
		/*
		 * 用这个fragment替换任何在fragment_container中的Fragment
		 * replace相当于remove(),然后add()方法。
		 */
		transaction.replace(R.id.receiveContainer, receiveFragment);
		/*
		 * transaction.addToBackStack(receiveFragment)时,会相当于activity存在栈中而响应back键,
		 * 如果你的activity中有一个fragment
		 * ,并且addToBackStack(receiveFragment)时,点击两次back键才能退出该activity
		 */
		transaction.addToBackStack(null);
		
		//向actvity添加sendFragment
		SendDataFragment sendFragment = new SendDataFragment();
		transaction.replace(R.id.sendContainer, sendFragment);
		
		// 提交事务
		transaction.commit();

	}

	@Override
	public void onArticleSelected(int position) {
		// TODO Auto-generated method stub
		// 做一些必要的业务操作

		// 使用静态fragment
		ReceiveDataFragment receiveFrag = (ReceiveDataFragment) getFragmentManager()
				.findFragmentById(R.id.receiveContainer);

		if (receiveFrag != null) {
			// 如果 article frag 不为空,那么我们在同时显示两个fragmnet的布局中...

			// 调用ReceiveDataFragment中的方法去更新它的内容
		} else {

			FragmentTransaction transaction = getFragmentManager().beginTransaction();

			ReceiveDataFragment receiveFragment = new ReceiveDataFragment();
			Bundle args = new Bundle();
			args.putInt(ReceiveDataFragment.ARG_POSITION, 88);
			/*
			 * Activity重新创建时,会重新构建它所管理的Fragment,原先的Fragment的字段 将会全部丢失,但是通过
			 * Fragment.setArguments(Bundle bundle)方法设 置的bundle会保留下来。所以尽量使用
			 * Fragment.setArguments(Bundle bundle)方式来传递参数
			 */
			receiveFragment.setArguments(args);
			/*
			 * 用这个fragment替换任何在fragment_container中的Fragment
			 * replace相当于remove(),然后add()方法。
			 */
			transaction.replace(R.id.receiveContainer, receiveFragment);
			/*
			 * transaction.addToBackStack(receiveFragment)时,会相当于activity存在栈中而响应back键,
			 * 如果你的activity中有一个fragment
			 * ,并且addToBackStack(receiveFragment)时,点击两次back键才能退出该activity
			 */
			transaction.addToBackStack(null);
			// 提交事务
			transaction.commit();
		}
	}

}


/**
 * @author ZhangFei
 * @version 2015-5-13 下午10:58:29
 */
@SuppressLint("NewApi")
public class SendDataFragment extends Fragment {

	// mCallback作为全局变量,方便访问Activity
	private OnHeadlineSelectedListener mCallback;

	// 用来存放fragment的Activtiy必须实现这个接口
	public interface OnHeadlineSelectedListener {
		public void onArticleSelected(int position);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// 这是为了保证Activity容器实现了用以回调的接口。如果没有,它会抛出一个异常。
		try {
			mCallback = (OnHeadlineSelectedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnHeadlineSelectedListener");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.activity_main, container, false);
		Button btn = (Button) view.findViewById(R.id.btn);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (mCallback != null) {
					// 发送数据给Activity宿主
					mCallback.onArticleSelected(1);
				}
			}
		});

		return view;
	}
}

/** 
 * @author ZhangFei
 * @version 2015-5-13 下午10:58:29
 */
@SuppressLint("NewApi")
public class ReceiveDataFragment extends Fragment{
	
	public static final String ARG_POSITION = "ARG_POSITION";
	
	// mCallback作为全局变量,方便访问Activity
	private int intValue;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// onCreate it's a good point to read the arguments
		Bundle b = getArguments();
		this.intValue = b.getInt(ReceiveDataFragment.ARG_POSITION);
	}
}



 There are another way you can add a fragment to the activity layout:

In this case, you can specify layout properties for the fragment as if it were a view. For example, here's the layout file for an activity with two fragments:

<?xml version="1.0" encoding="utf-8"?>
<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.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>


 

 








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值