向另一个活动发送多个变量值

4

这是我用来将字符串变量的值传递到另一个活动中的代码。

            Intent requestLink = new Intent(Search.this, Results.class);
            requestLink.putExtra("Link", sendLink);
            startActivity(requestLink);

但是如果我想传递多个变量怎么办呢?

            Intent requestLink = new Intent(Search.this, Results.class);
            requestLink.putExtra("Link", sendLink);
            startActivity(requestLink);


            Intent userSearch = new Intent(Search.this, Results.class);
            userSearch.putExtra("Search", addressInput);
            startActivity(userSearch);

使用以上的代码两次将只启动两个单独的活动。那么,我如何同时传输值呢?

我对Android开发和OOP还是很新手。

5个回答

3

您可以为同一个意图(intent)添加多个putExtra:

    Intent requestLink = new Intent(Search.this, Results.class);
    requestLink.putExtra("Link", sendLink);
    requestLink .putExtra("Search", addressInput);
    startActivity(requestLink);

3
btnlogin.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent=new Intent(getBaseContext(),db.class);
             String username=uname.getText().toString();
             String upaswrd=pass.getText().toString();
            // Bundle bundle=new Bundle();

          intent.putExtra(name,username);
          intent.putExtra(paswrd, upaswrd);

          startActivity(intent);
        }
    });


/** Db.class */

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.db);
    Intent intent=getIntent();
    String uname=intent.getStringExtra(Gmail.name);
    String upass=intent.getStringExtra(Gmail.paswrd);
    username=(TextView)findViewById(R.id.u);
    username.setText(uname);
    pass=(TextView)findViewById(R.id.p);
    pass.setText(upass);

}

2

只需将两个字符串放在同一个意图中。

Intent intent = new Intent(Search.this, Results.class);
intent.putExtra("Link", sendLink);
intent.putExtra("Search", addressInput);

startActivity(intent);

2
你可以使用Bundle在你的活动之间发送数据。 例如:
Intent requestLink = new Intent(Search.this, Results.class);

Bundle bun = new Bundle();
bun.putString("Link",sendLink);
bun.putString("Search", addressInput);

requestLink.putExtras(bun);
startActivity(requestLink);

请在这里查看Bundle API文档。


2
Intent requestLink = new Intent(Search.this, Results.class);
requestLink.putExtra("Link1", sendLink1);
requestLink.putExtra("Link2", sendLink2);
startActivity(requestLink);

//Second Activity 

Bundle bundle=getIntent().getExtras();
String Link1 =bundle.getString("Link1");
String Link2 =bundle.getString("Link2");

bundle.get...有很多重载,如getInt等,根据需要选择使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接