Intent之使用Extra属性在组件之间传递数据

时间:2022-08-21 16:26:35
第一步:

在MainActivity中使用Intent封装数据并传到第二个Activity

package com.example.intent;

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

public class MainActivity extends Activity {
private EditText m_Id_et,m_Name_et,m_Salary_et;
private Button m_btn_ok;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_Id_et = (EditText) findViewById(R.id.et_id);
m_Name_et = (EditText) findViewById(R.id.et_name);
m_Salary_et = (EditText) findViewById(R.id.et_salary);
m_btn_ok = (Button) findViewById(R.id.btn_ok);

m_btn_ok.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id;String name;float salary;
id = Integer.valueOf(m_Id_et.getText().toString());
name = m_Name_et.getText().toString();
salary = Float.valueOf(m_Salary_et.getText().toString());

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
/*
* 第二种方式使用Bundle封装数据
*/
Bundle bundle = new Bundle();
bundle.putInt("id", id);
bundle.putString("name", name);
bundle.putFloat("salary",salary);
intent.putExtras(bundle);

//第一种方式直接使用intent.putExtra封装,这种方式本质也是操作Bundle)

//intent.putExtra("id", id);
//intent.putExtra("name", name);
//intent.putExtra("salary", salary);
startActivity(intent);

}
});

}
}


第二步,在第二个Activity中接受数据并显示

package com.example.intent;

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

public class SecondActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

Intent intent = getIntent();/*
注意这里是使用getIntent()获取传过来的Intent对象,
Intent在激活一个Activty组件时会把intent对象也传过去
*/
int id = intent.getIntExtra("id", -1);
String name = intent.getStringExtra("name");
float salary = intent.getFloatExtra("salary", -1f);

((TextView) findViewById(R.id.tv_id)).setText("id为"+id);
((TextView) findViewById(R.id.tv_name)).setText("name"+name);
((TextView) findViewById(R.id.tv_salary)).setText("salary"+salary);
}
}