活动与活动之间传递参数以及活动界面的跳转,都用到Intent,
这里我们先创建活动,在活动MainActivity中生成一个按钮用于传递参数以及界面的跳转
intent主要用了以下方法进行传输:
以下是单一参数的传输:
Intent intent =new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("key","value");
startActivity(intent);
多个参数的传输通过bundle这一媒介来进行传输:
Bundle bundle =new Bundle();
bundle.putString("key","value");
bundle.putString("key2","value2");
intent.putExtras(bundle);
package com.game.intent822;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Bundle bundle =new Bundle();
bundle.putString("name","jack");
bundle.putString("name2","job");
Button button = new Button(this);
layout=(LinearLayout)findViewById(R.id.layout);
layout.addView(button);
button.setText("send");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
然后在SecondActivity中对传输的参数进行接收,
Intent intent =getIntent();
intent.getStringExtra("key");
package com.game.intent822;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView textView=(TextView)findViewById(R.id.tv);
Intent intent = getIntent();
String item =intent.getStringExtra("name");
String item2=intent.getStringExtra("name2");
textView.setText(item+" \n"+item2);
}
}