0%

用Intent在不同Activity间传送数据(主类型、对象)Serializable接口

需要在不同的Activity中传送数据,可以在原Activity用Intent跳转到新Activity的时候,附加上数据,然后在新的Activity中就可以接收到。 下面以main跳转到NA为例: main.java中代码:

            Intent intent=new Intent();
            //生成一个Intent对象
            intent.setClass(main.this, NA.class);
            //本Activity为main,目标Activity为NA
            intent.putExtra("et1", et1.getText().toString());
            //et1是一个文本输入框,et2也是一样
            intent.putExtra("et2",et2.getText().toString());
            main.this.startActivity(intent);
            //启动跳转

NA.java接收数据:

        Intent intent=getIntent();
        //取得传过来的Intent
        String et1=intent.getStringExtra("et1");
        String et2=intent.getStringExtra("et2");
        //获取et1,et2数据
        TextView tv=(TextView)findViewById(R.id.tv2);
        tv.setText("et1="+et1+"   et2="+et2);
        //将结果显示在tv2这个TextView中

传送数据还可以用Bundle,用法差不多,参见Android开发中插入新的Activity 如果需要传送是的是个对象,则必须用Bundle:

typeVideo tv_play=new typeVideo();
Intent intent = new Intent();
intent.setClass(context,VideoPlayer.class);
Bundle bundle=new Bundle();
bundle.putSerializable("tv_play",tv_play);
intent.putExtras(bundle);
context.startActivity(intent);

typeVideo类必须实现Serializable接口,如果typeVideo有用到其他类的对象,则该类也需要实现Serializable接口。 接收:

typeVideo tv_play=(typeVideo)getIntent().getSerializableExtra("tv_play");