Fragment 和Activity的数据传递实例代码
package com.example.fragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends FragmentActivity { private Fragment01 f1; private EditText etContent; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etContent = (EditText) findViewById(R.id.et_conent); tv = (TextView) findViewById(R.id.tv); // 1. 创建fragment对象 ragment01 f1 = new Fragment01(); // 2. 获取fragment管理器 FragmentManager fm = this.getSupportFragmentManager(); // 3. 获取事务 FragmentTransaction ft = fm.beginTransaction(); // 4. 设置布局 ft.replace(R.id.fl, f1); // 5. 提交 ft.commit(); } /** * 给textview设置fragment02传递过来的数据 */ public void setText(String text){ tv.setText(text); } /** * 获取fragment01对象,调用给textview设置数据的方法 */ public void send(View v){ String text = etContent.getText().toString().trim(); f1.setText(text); //将数据传递给fragment } public void message(View v){ // 1. 创建fragment对象 f1 = new Fragment01(); // 2. 获取fragment管理器 FragmentManager fm = this.getSupportFragmentManager(); // 3. 获取事务 FragmentTransaction ft = fm.beginTransaction(); // 4. 设置布局 ft.replace(R.id.fl, f1); // 5. 提交 ft.commit(); } }
package com.example.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; 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; /** * 联系人 */ public class Fragment02 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_contacts, null); final EditText etContent = (EditText) view.findViewById(R.id.et_conent); Button btn = (Button) view.findViewById(R.id.btn); //设置按钮的点击事件 btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String text = etContent.getText().toString().trim(); //获取f2所依附的activity的对象 MainActivity activity = (MainActivity) getActivity(); activity.setText(text);//将数据传递给activity中 } }); return view; } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!