我想将值从一个页面传递到另一个页面,我的代码是:
public class main extends Activity implements OnClickListener {
private static final String TAG = "AskMeShowMe2";
private String choice = null;
private String fname = null;
private Menu myMenu = null;
final static int START =0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG,"Main - onCreate() ...");
setContentView(R.layout.activity_main);
View promptButton = findViewById(R.id.submit_button);
promptButton.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.greetingsRadioGroup);
int checkedRadioButton = radioGroup.getCheckedRadioButtonId();
switch (checkedRadioButton) {
case R.id.mrButton :
choice = "Mr.";
break;
case R.id.mrsButton :
choice = "Mrs.";
break;
case R.id.msButton:
choice = "Ms.";
break;
case R.id.drButton:
choice = "Dr.";
break;
}
switch(v.getId()){
case R.id.submit_button:
Intent j = new Intent(this, Info.class);
j.putExtra("choice", choice);
startActivity(j);
fname=String.valueOf(R.id.firstname);
Intent t = new Intent(this, Info.class);
j.putExtra("fname", fname);
startActivity(t);
break;
}
}
和其他Info.Class:
public class Info extends Activity {
private static final String TAG = "Info";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
Intent myIntent = getIntent();
Bundle b = myIntent.getExtras();
String choice = b.getString("choice");
String fname = b.getString("fname");
Log.i(TAG,"selection: " + choice);
TextView textView = (TextView) findViewById(R.id.showmeText);
textView.append(": " + choice);
TextView textView1 = (TextView) findViewById(R.id.fname);
textView1.append(": " + fname);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
return true;
}
}
当我运行这个程序时,当我点击提交按钮时,我的Info.class页面没有显示,你能帮我解决一下吗?
答案 0 :(得分:1)
使用
Intent j = new Intent(this, Info.class);
j.putExtra("choice", choice);
fname=String.valueOf(R.id.firstname);
j.putExtra("fname", fname);
startActivity(j);
而不是
Intent j = new Intent(this, Info.class);
j.putExtra("choice", choice);
startActivity(j);
fname=String.valueOf(R.id.firstname);
Intent t = new Intent(this, Info.class);
j.putExtra("fname", fname);
startActivity(t);
因为目前你正在为intent j
首次调用startActivity两次,而intent t
则第二次调用startActivity,所以删除一个并将select和fname放在单个intent中并仅调用startActivity一次。
答案 1 :(得分:1)
将切换块更改为以下内容:
switch(v.getId()){
case R.id.submit_button:
Intent j = new Intent(this, Info.class);
j.putExtra("choice", choice);
fname=String.valueOf(R.id.firstname);
j.putExtra("fname", fname);
startActivity(j);
break;
}
当您启动活动信息两次时,将额外内容仅添加到一个意图中,该意图正在提前启动。