传值
// 显示意图
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);
}
本文详细介绍了在Android应用中如何通过Intent和Bundle进行数据传递。首先展示了如何在Intent中使用`putExtra`方法传递字符串数据,然后在SettingActivity中通过`getIntent`和`getStringExtra`接收并打印数据。接着,演示了使用Bundle进行数据封装和解封,将数据以键值对形式存入Intent,并在接收端通过`getExtras`获取数据。这个过程对于Android开发者理解和实现组件间的数据交互至关重要。
969

被折叠的 条评论
为什么被折叠?



