GoldGold

阳哥的移动开发之旅

Fragment向activity中传值

Fragment向activity中传值

1.在Fragment中写一个回调接口  

2.在activity中实现这个回调接口

3,在Fragment中onAttach 方法中得到activity中实现好的 实例化接口对象

4,用接口的对象  进行传值


代码:

MainActivity:


package com.qianfeng.fragmenttoactivity;

import com.qianfeng.fragmenttoactivity.Fragmen1.CallBackValue;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;
import android.widget.TextView;

@SuppressLint("NewApi") 
public class MainActivity extends Activity implements CallBackValue{

	private TextView tv1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tv1 = (TextView) findViewById(R.id.tv1);
        
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        
        transaction.add(R.id.contents, new Fragmen1());
        transaction.commit();
        
    }
    //要获取的值  就是这个参数的值
	@Override
	public void SendMessageValue(String strValue) {
		// TODO Auto-generated method stub
		tv1.setText(strValue);
	}


    
}

Fragment:

package com.qianfeng.fragmenttoactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
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.EditText;

@SuppressLint("NewApi") 
public class Fragmen1 extends Fragment{
	private Button btn1;
	private EditText et1;
	CallBackValue callBackValue;
	
	/**
	 * fragment与activity产生关联是  回调这个方法 
	 */
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		//当前fragment从activity重写了回调接口  得到接口的实例化对象
		callBackValue =(CallBackValue) getActivity();
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_layout1, container, false);
		 btn1 = (Button) view.findViewById(R.id.btn1);
		 et1 = (EditText) view.findViewById(R.id.et1);
		 btn1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String strValue = et1.getText().toString().trim();
				callBackValue.SendMessageValue(strValue);
			
			}
		});
		
		return view;
	}
	//定义一个回调接口
	public interface CallBackValue{
		public void SendMessageValue(String strValue);
	}
}



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shanxuyang/article/details/47113773
文章标签: android
个人分类: Android基础知识
上一篇Activity向Fragment中传值
下一篇Fragment向Fragment传值(第一种)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭