Android 跳转Activity并通过Bundle对象传递数据

时间:2021-10-13 23:42:35

1)Activity1 (MainActivity)

package com.example.androidtestproject;


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


public class MainActivity extends Activity {


private EditText UsernameTextEdit=null;
private EditText PasswordTextEdit=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button loginButton=(Button)findViewById(R.id.loginButton);
UsernameTextEdit=(EditText)findViewById(R.id.UsernameEditText);
PasswordTextEdit=(EditText)findViewById(R.id.PasswordeEditText);

loginButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View view){

String username=UsernameTextEdit.getText().toString();
String password=PasswordTextEdit.getText().toString();

/*new 一个Intent对象,并制定要启动的class*/
Intent intent=new Intent();
intent.setClass(MainActivity.this, TestActivity.class);

/*new 一个Bundle对象,并将要传递的数据传入*/
Bundle bundle=new Bundle();
bundle.putString("username", username);
bundle.putString("password",password);

/*将Bundle对象assign给Intent*/
intent.putExtras(bundle);

/*调用一个新的Activity*/
startActivity(intent);
/*关闭原来的Activity*/
MainActivity.this.finish();
}
});
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

2)Activity2 (TestActivity)

package com.example.androidtestproject;


import android.app.Activity;
import android.os.Bundle;
import android.widget.*;


public class TestActivity extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_test);
TextView UsernameTextView=(TextView)findViewById(R.id.TestUsernameTextView);
TextView PasswordTextView=(TextView)findViewById(R.id.TestPasswordTextView);

/*获取Intent中的Bundle对象*/
Bundle bundle=this.getIntent().getExtras();

/*获取Bundle对象中的数据*/
String username=bundle.getString("username");
String password=bundle.getString("password");

/*将数据和控件绑定*/
UsernameTextView.setText(username);
PasswordTextView.setText(password);
}


}