安卓开发:Activity之间的切换和传值

时间:2021-09-09 22:42:18

首先先把按钮布局好,自己怎么好看怎么来

安卓开发:Activity之间的切换和传值

这是第一个活动的界面,需要使用intent和bundle

package com.example.activity1;

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

public class MainActivity extends Activity {
private Button but;
private RadioButton rad;
private EditText edi;
private String sex,name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but=(Button)findViewById(R.id.button1);
rad=(RadioButton)findViewById(R.id.radio0);
edi=(EditText)findViewById(R.id.editText1);
but.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO 自动生成的方法存根
if(rad.isChecked()){
sex="男";
}else sex="女";
name=edi.getText().toString();
Intent intent=new Intent(MainActivity.this,MainActivity2.class);
Bundle bud=new Bundle();
bud.putString("姓名", name);
bud.putString("性别", sex);
intent.putExtras(bud);
startActivity(intent);
}
});
}
@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;
}

}

建立第二个活动,当时上课我没在意,老师创建完了我才缓过来,然后百度吧也找不到,自己就直接new一个android Activity.

不知道是否有啥弊端,我看了下androidmanifest里面也自动给我创建好了活动

直接上代码吧!

package com.example.activity1;

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

public class MainActivity2 extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
Intent intent=this.getIntent();
TextView txt=(TextView)findViewById(R.id.textView);
String name=intent.getStringExtra("姓名");
String sex=intent.getStringExtra("性别");
txt.setText("您的性别为:"+sex+"\r\n"+"姓名:"+name);
}

@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_activity2, menu);
return true;
}

}