标签:return str 调用 create undle ring inf oncreate tran
在activity中加载 frament,并传递给它参数
//setArguments //1.实例化Fragment Fragment f1 = new Fragment1(); //2.实例化一个Bundle对象 Bundle bundle = new Bundle(); //3.存入数据到Bundle对象中 bundle.putString("msg1","这是由Activity发往Fragment的数据"); //4.调用Fragment的setArguments方法,传入Bundle对象 f1.setArguments(bundle); //5.添加/替换显示的Fragment transaction.replace(R.id.container,f1);
在fragment.java, 接收到参数
//Fragment创建视图 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment Log.e("TAG","onCreateView--Fragment视图创建好了"); View v = inflater.inflate(R.layout.fragment_fragment1, container, false); Bundle b = getArguments(); String msg1 = b.getString("msg1"); ((TextView)v.findViewById(R.id.txt1)).setText(msg1); return v; }
也可以通过 public void onAttach(Context context)
来得到activity,然后操作activity。
MainActivity.java
public class MainActivity extends AppCompatActivity {
public String msg = "How are you ";
}
fragment.java
@Override public void onAttach(Context context) { super.onAttach(context); String msg = ((MainActivity)context).msg; Toast.makeText(context,msg,Toast.LENGTH_SHORT).show(); Log.e("TAG","onAttach--Fragment与Activity关联"); }
标签:return str 调用 create undle ring inf oncreate tran
原文地址:https://www.cnblogs.com/yuguangyuan/p/13226486.html