Fragment向Fragment传值(第三种)

因为  fragment1 和fragment2  都在Activity中   所以可以根据Activity得到里面的控件



代码

Fragment1:


package com.qianfeng.fragmenttofragment2;

import android.annotation.SuppressLint;
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;
import android.widget.TextView;

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

	private Button btn1;
	private EditText et1;

	@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 strValues = et1.getText().toString().trim();
				// 通过fragment指定的id 找到Fragment对象 通过getView()方法 得到view 
				//通过findViewById() 找到控件
//				Fragment2 fragment2 = (Fragment2) getFragmentManager()
//						.findFragmentById(R.id.fg2);
//				TextView tv_show = (TextView) fragment2.getView().findViewById(
//						R.id.tv_show);
				
				//因为  fragment1 和fragment2  都在Activity中   所以可以根据Activity得到里面的控件
				TextView tv_show  = (TextView) getActivity().findViewById(R.id.tv_show);
				tv_show.setText(strValues);
			}
		});
		return view;
	}
}

Fragment2:


package com.qianfeng.fragmenttofragment2;

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

@SuppressLint("NewApi")
public class Fragment2 extends Fragment{
	
	private TextView tv_show;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_layout2, container, false);
		tv_show = (TextView) view.findViewById(R.id.tv_show);
		return view;
	}
	
}



你可能感兴趣的:(Android基础知识)