(三)页面之间的参数传递

一、页面跳转

1、没有返回值的

打开Aty1

//跳转Aty1
Intent i=new Intent(MainActivity.this,Aty1.class);
//打开
startActivity(i);

关闭Aty1

finish();

 

 

2、有返回值的

打开Aty1并传入字符串

private Button btnStartAty1;
    private TextView tvOut;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnStartAty1=(Button)findViewById(R.id.btnStartAty1);
        tvOut=(TextView)findViewById(R.id.tvOut);
        btnStartAty1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i=new Intent(MainActivity.this,Aty1.class);
                //传递字符串
                i.putExtra("txt", "adkj");
                //打开activity并可以接收返回的值
                startActivityForResult(i,0);
            }
        });
    }

    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //接收字符串
        String result=data.getStringExtra("result");

        tvOut.setText(result);
        super.onActivityResult(requestCode, resultCode, data);
    }

Aty1返回信息

private Button btnClose;
    private TextView tvOut;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty1);

        btnClose=(Button)findViewById(R.id.btnClose);
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i=new Intent();
                i.putExtra("result","Hello MainActiviy");
                //发送返回值
                setResult(0,i);

                finish();
            }
        });

        tvOut=(TextView)findViewById(R.id.tvOut);
        tvOut.setText(getIntent().getStringExtra("txt"));

    }

 

 

二、参数传递

1、方法一

//跳转Aty1
Intent i=new Intent(MainActivity.this,Aty1.class);
//传递参数
i.putExtra("txt", "adkj");

//打开
startActivity(i);

接收参数

getIntent().getStringExtra("txt")

 

2、方法二

Intent i=new Intent(MainActivity.this,Aty1.class);

Bundle data=new Bundle();
data.putString("txt","Hello Aty1");
i.putExtras(data);

startActivity(i);

接收参数

Bundle data=getIntent().getExtras();
String txt=data.getString("txt");

 

posted @ 2015-10-30 09:57  岳帅超  阅读(199)  评论(0编辑  收藏  举报