一、Activity之间传递数据
1、使用Intent传递一般数据(如字符串)
(1)发送数据
Intent intent = new Intent(this,SecondActivity.class);intent.putExtra("data","sldkjfoei");startActivity(intent);
(2)接收数据
Intent intent = getIntent();String data = intent.getStringExtra("data");
2、传递Bundle
(1)发送数据
Intent intent = new Intent(this,SecondActivity.class);Bundle bundle = new Bundle();bundle.putString("data","将数据放到Bundle中");intent.putExtra("bundle",bundle);startActivity(intent);
(2)接受数据
Intent intent = getIntent();Bundle bundle = intent.getBundleExtra("bundle");bundle.getString("data");
3、传递对象
(1)这个对象要实现序列化(2)发送一个实现了序列化的Student类对象
Intent intent = new Intent(this, SecondActivity.class);Student student = new Student("name",12,"gender");intent.putExtra("student",student);startActivity(intent);
(3)接受对象
Intent intent = getIntent();Serializable student = intent.getSerializableExtra("student");
4、从Activity返回数据
(1)启动另一个Activity用startActivityForResult()
startActivityForResult(intent, 0);//这里采用startActivityForResult来做跳转,此处的0为一个依据,可以写其他的值,但一定要>=0
(2)在另一个Activity中调用setResult方法,将要返回的数据传进来
setResult(RESULT_OK, intent); //intent为A传来的带有Bundle的intent,当然也可以自己定义新的Bundlefinish();//此处一定要调用finish()方法
(3)在原Activity中重写onActivityResult()方法获取数据
protected void onActivityResult(int requestCode, int resultCode, Intent data) {switch (resultCode) { //resultCode为回传的标记,我在B中回传的是RESULT_OKcase RESULT_OK:Bundle b = data.getExtras(); //data为B中回传的IntentString str = b.getString("str1");//str即为回传的值break;default:break;}}
二、Activity与Fragment之间的交互(Fragment依赖于这个Activity)
1、Fragment获取Activity中的数据
1.1 Activity创建Fragment实例时传递数据
(1)MyFragment中写一个创建实例的方法,在方法中使用Bundle存储Activity传过来的数据
public static MyFragment newInstance(String data){MyFragment myFragment = new MyFragment();Bundle bundle = new Bundle();bundle.putString("id",data);myFragment.setArguments(bundle);return myFragment;}
(2)在MyFragment的onCreateView()方法中获取数据
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {Bundle bundle = getArguments();String text = bundle.getString("id");return super.onCreateView(inflater, container, savedInstanceState);- }
(3)在Activity中创建MyFragment实例,传入需要传递给MyFragment的数据
//这里只需要直接调用这个方法,就创建了一个fragmentfragment = MyFragment.newInstance("这里是要传递给MyFragment的数据");
1.2 Activity中实例化Fragment后发送数据
(1)Activity中:
MyFragment fragment = new MyFragment();Bundle bundle = new Bundle();bundle.putString("id","从Activity中发送到Fragment的数据");、fragment.setArguments(bundle);
(2)MyFragment中:
Bundle bundle = getArguments();String text = bundle.getString("id"));
1.3 在Fragment中定义回调接口,Activity中实现接口
(1)在MyFragment中定义回调接口:
interface MyFragmengListener{void onCallBack();}MyFragmengListener fragmengListener = null;
(2)在MyFragment中需要的地方调用回调方法,比如在一个Button的点击事件中
btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {fragmengListener.onCallBack();}});
(3)在Activity中实现回调接口,在回调方法中编写要执行的操作或设置要传递的数据
public class MainActivity extends AppCompatActivity implements MyFragment.MyFragmengListener {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic void onCallBack() {// 可以做很多操作,比如启动另一个Fragment,发送数据到Fragment中等等Toast.makeText(getApplicationContext(),"Fragment获取到Activity中的数据",Toast.LENGTH_SHORT).show();}}
(1)发送数据的Activity中
1.4 使用剪切板
Person person = new Person("wulianghuan","22");//将对象转换成字符串ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();String base64String = "";try {ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);objectOutputStream.writeObject(person);base64String = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);objectOutputStream.close();} catch (IOException e) {e.printStackTrace();}//从Android系统中调用剪切板的服务ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);//在剪切板中放入要传递的数据clipboardManager.setText(base64String);//定义一个意图Intent intent = new Intent(MainActivity.this,OtherActivity.class);startActivity(intent);
(2)接受数据的Activity
//从Android系统中调用剪切板的服务ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);String getString = clipboardManager.getText().toString();//字符串还原成对象byte[] base64_byte = Base64.decode(getString, Base64.DEFAULT);ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64_byte);try {ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);Person person = (Person)objectInputStream.readObject();Log.i("OtherActivity", person.toString());//设置文本框的数据text_name.setText(person.toString());} catch (StreamCorruptedException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}
1.5 发送广播
1.6 使用静态变量
2、Activity获取Fragment中的数据
(1)创建一个广播管理类2.1 发送广播
/*** 广播管理类:注册广播、注销广播、发送广播* @author weizh_000* @date 2016-8-29*/public class BroadCastManager {private static BroadCastManager broadCastManager = new BroadCastManager();public static BroadCastManager getInstance() {return broadCastManager;}//注册广播接收者public void registerReceiver(Activity activity,BroadcastReceiver receiver, IntentFilter filter) {activity.registerReceiver(receiver, filter);}//注销广播接收者public void unregisterReceiver(Activity activity,BroadcastReceiver receiver) {activity.unregisterReceiver(receiver);}//发送广播public void sendBroadCast(Activity activity, Intent intent) {activity.sendBroadcast(intent);}}
(2)在Fragment中发送广播
public class MyFragment extends Fragment {private String orderid = "85465465";@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {//发送广播Intent intent = new Intent();intent.putExtra("order", orderid);intent.setAction("fragment_home_left");BroadCastManager.getInstance().sendBroadCast(getActivity(), intent);return super.onCreateView(inflater, container, savedInstanceState);}}
(3)在Activity中接收广播
public class MainActivity extends ActionBarActivity {private LocalReceiver mReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//接收广播try {IntentFilter filter = new IntentFilter();filter.addAction("fragment_home_left");mReceiver = new LocalReceiver();BroadCastManager.getInstance().registerReceiver(this,mReceiver, filter);//注册广播接收者} catch (Exception e) {e.printStackTrace();}}class LocalReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {//收到广播后的处理String orderid = intent.getStringExtra("order");loadData(orderid);}}private void loadData(String orderid){}@Overrideprotected void onDestroy() {BroadCastManager.getInstance().unregisterReceiver(this,mReceiver);//注销广播接收者super.onDestroy();}}
2.2 Activity中使用Fragment对象获取数据
如果没有Fragment对象可以使用getFragmentByTag()方法来获取对象
三、Fragment之间的交互
1、依赖于同一个Activity的Fragment
1.1 发送广播
1.2 先获取到依赖的Activity,在获取到对应的Fragment
(1)发送数据
ft.hide(getActivity().getSupportFragmentManager().findFragmentByTag(“”));SearchProjectFragment sf = new SearchProjectFragment();Bundle bundle = new Bundle();bundle.putString("key", Projsid);sf.setArguments(bundle);ft.add(R.id.fragmentRoot, sf, SEARCHPROJECT);ft.addToBackStack(SEARCHPROJECT);ft.commit();
(2)接收数据
String string = getArguments().getString("key");
1.3 使用EventBus
2、依赖于不同的Activity的Fragment
2.1 发送广播
2.2 综合上述传递方式
Activity01获取Fragment01中的数据然后发送给Acticity02,Fragment02从Activity02获取从Activity01获取到的数据
本文详细探讨了Android中Activity与Fragment之间以及Fragment之间的数据传递方法,包括使用Intent、Bundle、对象、回调接口、剪切板、广播、静态变量、EventBus等多种策略,覆盖了不同场景下的数据交互需求。
9647

被折叠的 条评论
为什么被折叠?



