您的位置:首页 > 其它

Fragment向Fragment传值(第二种)

2015-07-28 23:10 387 查看
通过fragment指定的id 找到Fragment对象

代码

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;

@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对象
Fragment2 fragment2 =(Fragment2) getFragmentManager().findFragmentById(R.id.fg2);
fragment2.putValues(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;
}
//这个方法是 对tv_show 进行赋值
public void putValues(String strValues){
tv_show.setText(strValues);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: