如何在Android开发中activity之间数据传递

2024-10-30 23:44:43
推荐回答(1个)
回答1:

从一个Activity(IntentDemo)跳转到另外一个Activity(Other),其中利用Intent来传递数据
程序Demo如下:
IntentDemo.java
package com.android.intentdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class IntentDemo extends Activity {

private Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initComponent();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(IntentDemo.this, Other.class);
// 在Intent中传递数据
intent.putExtra("name", "AHuier");
intent.putExtra("age", 22);
intent.putExtra("address", "XiaMen");
// 启动Intent
startActivity(intent);
}
});
}

private void initComponent() {
button = (Button) findViewById(R.id.button);

}
}

other.java
package com.android.intentdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class Other extends Activity {

private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
initComponent();

Intent intent = getIntent();
int age = intent.getIntExtra("age", 0);
String name = intent.getStringExtra("name");
String address = intent.getStringExtra("address");

textView.setText("My age is " + age + "\n" + "My name is " + name + "\n" + "My address "
+ address);
}

private void initComponent() {

textView = (TextView) findViewById(R.id.msg);
}
}