切换意图时,我丢失了前一个 onActivityResult 的数据,我需要它来保留从用户那里获得的两个数字,目前它会保留一个数字,然后当输入下一个数字时,它会丢失前一个数字,这里是代码:
package com.eric.theworks;
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.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button width, height, calc;
TextView area;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
width = (Button) findViewById(R.id.button1);
height = (Button) findViewById(R.id.button2);
calc = (Button) findViewById(R.id.button3);
area = (TextView) findViewById(R.id.textView1);
width.setOnClickListener(this);
height.setOnClickListener(this);
calc.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(this, Numbers.class);
switch (v.getId()) {
case R.id.button1:
// width
i.putExtra("numbers", "width");
startActivityForResult(i, 1);
break;
case R.id.button2:
// height
i.putExtra("numbers", "height");
startActivityForResult(i, 1);
break;
case R.id.button3:
// calc
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (data.getExtras().containsKey("widthInfo")){
width.setText(data.getStringExtra("widthInfo"));
}
if (data.getExtras().containsKey("heightInfo")){
height.setText(data.getStringExtra("heightInfo"));
}
}
}
package com.eric.theworks;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Numbers extends Activity implements OnClickListener {
EditText number;
Button sendInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.numbers);
number = (EditText) findViewById(R.id.editText1);
sendInfo = (Button) findViewById(R.id.button1);
sendInfo.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = number.getText().toString();
Intent i = getIntent();
String msg = i.getStringExtra("numbers");
if (msg.contentEquals("width")) {
i.putExtra("widthInfo", s);
setResult(RESULT_OK, i);
finish();
}
if (msg.contentEquals("height")) {
i.putExtra("heightInfo", s);
setResult(RESULT_OK, i);
finish();
}
}
}