Fragment间回调传值

        在Android开发中,会经常用到android碎片Fragment进行项目UI的搭建。那么fragment之间的数据传递可以采用多种的方式来实现。自己总结的一个利用回调函数实现fragment与activity通信的Demo。

           具体代码如下:

1.宿主Activity的布局文件如下:

activity_callback.xml

<span style="font-size:14px;"><?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" >
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        >
        
        <fragment 
            android:id="@+id/frag_one"
            android:name="com.jingchen.tbviewer.fragment.OneFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="2"
            />
        <fragment android:id="@+id/frag_two"
            android:name="com.jingchen.tbviewer.fragment.TwoFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            />
        
        
        
    </LinearLayout>
    
    

</LinearLayout>
</span>

2.  Activity的相关代码:

<span style="font-size:18px;">package com.jingchen.tbviewer.ui;

import com.jingchen.tbviewer.R;
import com.jingchen.tbviewer.fragment.OneFragment.MyChangeListener;
import com.jingchen.tbviewer.fragment.TwoFragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.widget.Toast;
// 此处activity需实现OneFragment中定义的接口
public class CallBackActivity extends FragmentActivity implements MyChangeListener{
	
	@Override
	protected void onCreate(Bundle bundle) {
		
		super.onCreate(bundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.activity_callback);
		
	}

	@Override
	public void changeData(String content) {
		
		TwoFragment twoFragment=(TwoFragment) getSupportFragmentManager().findFragmentById(R.id.frag_two);
		if(twoFragment!=null){
			
			twoFragment.refeshData(content);
			
		}
		
		Toast.makeText(CallBackActivity.this, content, Toast.LENGTH_SHORT).show();
		
	}

}
</span>

3.OneFragment的相关代码:

public class OneFragment extends Fragment {
	private View view;
	private List<String> list;
	private ListView lvOne;
	private MyAdapter adapter;

	private MyChangeListener changeListener;
	
	// 重写onAttach方法,实例化接口对象
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		try{
			
			changeListener=(MyChangeListener) activity;
		}catch(ClassCastException e){
			 throw new ClassCastException(activity.toString()
	                    + " must implement MyChangeListener");
		}
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_one, container, false);

		lvOne = (ListView) view.findViewById(R.id.lv_one);
		list = new ArrayList<String>();
		
		lvOne.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int position,
					long id) {
				// ListView的置顶效果
				lvOne.setSelection(position);
//				lvOne.smoothScrollBy(v.getHeight()*position, 200);
//				lvOne.smoothScrollToPosition(position);
				// 传值
				changeListener.changeData(list.get(position));
				
				
			}
		});

		insertData();

		return view;
	}

	private void insertData() {
		for (int i = 0; i < 20; i++) {

			list.add("这是第" + i + "项");

			mhandler.sendEmptyMessage(0);
		}

	}

	private Handler mhandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				
				adapter=new MyAdapter(getActivity(), list);
				adapter.notifyDataSetChanged();
				lvOne.setAdapter(adapter);
				break;

			default:
				break;
			}

		};
	};
	
	
	
	//  自定义接口
	public interface MyChangeListener{
		public void changeData(String content);
		
	}

}

4.twoFragment中的代码:

public class TwoFragment extends Fragment{
	private TextView tvContent;
	
	private String myData;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view =inflater.inflate(R.layout.fragment_two, container, false);
		tvContent=(TextView) view.findViewById(R.id.tv_fragment);
		
		
		
		return view;
	}
	
	
	// 定义相应的方法。获取回调的值
	public void refeshData(String content){
		this.myData=content;
		tvContent.setText(content);
		Log.e("TwoFragment", myData);	
	}
	
	
	
	

}


5.模拟器运行效果图


           



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值