传值
// 显示意图
public void jumpToSetting(View view) {
/*从 MainActivity.this 到 SettingActivity.class*/
Intent intent = new Intent(MainActivity.this, SettingActivity.class);
// 传值
intent.putExtra("username", "周杰伦");
intent.putExtra("age", "12");
intent.putExtra("class", "guess");
/*跳转*/
startActivity(intent);
}
接收
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".SettingActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="设置页面"
android:textSize="30sp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="展示传递数据"
android:onClick="showInfo" />
</LinearLayout>
package com.example.activitytest;
public class SettingActivity extends AppCompatActivity {
private static final String TAG = "TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
}
// 接收
public void showInfo(View view) {
Intent intent = getIntent();
if (intent != null) {
String username = intent.getStringExtra("username");
Log.d(TAG, "onCreate: " + username);
}
}
}
打包 Bundle 传递
// 传递
public void byBundle(View view) {
Intent intent = new Intent(MainActivity.this, SettingActivity.class);
Bundle bundle = new Bundle();
bundle.putString("username", "pig");
bundle.putInt("age", 12);
intent.putExtras(bundle);
startActivity(intent);
}
// 接收
public void showBundleInfo(View view) {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
int age = bundle.getInt("age");
String username = bundle.getString("username");
Log.d(TAG, "showBundleInfo: " + age + username);
}