我需要一些关于我正在使用eclipse编写的应用程序的建议。我正在编写一个添加2个数字的应用程序,并使用intent将数据传回第一个活动。我不确定我是否使用intent.putExtra(num1 + num 2),任何建议将不胜感激。谢谢 -
答案 0 :(得分:1)
假设您从活动A转到活动B并且您想要将某些内容返回到活动A,那么这是一个示例。希望它有所帮助:
转到活动B o按钮的代码点击:
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);
//2 is the request code. u can choose ur own.
}
});
也在相同的活动覆盖onActivityResult方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
Int x = data.getIntExtra ("num1");
Int y = data.getIntExtra ("num2");
}
}
在你的活动B中
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Bundle b = new Bundle();
b.putIntExtra("num1", int1);
b.putIntExtra("num2", int2);
Intent i = new Intent();
i.put(b);
finish();//finishing activity
}
});
答案 1 :(得分:0)
您在第一项活动中需要这样做:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
int result=data.getIntExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
这是你班上的数学:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",sumOfNumbers);
setResult(RESULT_OK,returnIntent);
finish();
答案 2 :(得分:0)
您可以启动使用startActivityForResult()添加2个数字的Activity,然后实现onActivityResult()回调以接收结果。
在添加2个数字的Activity中,您可以使用setResult(resultCode,Intent)设置结果:
Intent returnIntent = new Intent();
returnIntent.putExtra("result", sum);
setResult(RESULT_OK,returnIntent);
finish();
查看Android文档:http://developer.android.com/training/basics/intents/result.html
答案 3 :(得分:0)
您需要使用父Activity类的onActivityResult函数。
int RESULT_CODE_CHILD_ACTIVITY = 1;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case (RESULT_CODE_CHILD_ACTIVITY) :
{
if (resultCode == Activity.RESULT_OK)
{
int yourInt = data.getIntExtra("yourInt", -1);
}
break;
}
}
}
并且您希望覆盖子活动的onDestroy函数以将数据传回。
@Override
public void onDestroy()
{
Intent resultIntent = new Intent();
int yourInt = 5 + 4;
resultIntent.putExtra(yourInt, "yourInt");
setResult(Activity.RESULT_OK, resultIntent);
super.onDestroy();
}