我在活动A中有一个列表视图。我想总结从活动B返回活动A的总金额,但我不知道如何添加它们。
double sum =0;
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
double ReceiveAmount = data.getDoubleExtra("amount",0);
sum = + ReceiveAmount;
totalAmount.setText(sum+")
}
}
}
}
假设在活动B中我返回金额5,然后我再次转到活动B并返回值10.我希望吐司显示值15而不是总是5。
修改
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
double ReceiveAmount = data.getDoubleExtra("amount",0);
sum += ReceiveAmount;
if (mClickedPosition == -1) { // if icon clicked
if (obj != null) {
obj.addNewItem(ReceiveAmount);
listview.setAdapter(obj);
Toast.makeText(getApplicationContext(),sum+"",Toast.LENGTH_SHORT).show();
addOrRemoveFooter(sum);
}
}
}
}
}
public void addOrRemoveFooter(double sum2) {
if (search.size() == 0 && listview.getFooterViewsCount() > 0) {
listview.removeFooterView(footerLayout);
Toast.makeText(getApplication(),"In"+sum2+"",Toast.LENGTH_SHORT).show();
} else if (listview.getFooterViewsCount() == 0 && search.size() > 0) {
Toast.makeText(getApplication(),"Out"+sum2+"",Toast.LENGTH_SHORT).show();
listview.addFooterView(footerLayout);
listview.setAdapter(obj);
totalAmount.setText(sum2 + "");
}
else
{
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
}
吐司现在显示15,但是setText总是5 ...为什么?
首先,一切似乎都很好,因为它在Out
addOrRemoveFooter
中显示Toast.makeText(getApplication(),"Out"+sum2+"",Toast.LENGTH_SHORT).show();
,但是当我第二次添加时会显示error
。
答案 0 :(得分:3)
首先以这种方式使用startActivityForResult开始您的活动。
private static final int RC_B = 123;
Intent intent = new Intent(ActivityA.this, ActivityB.class);
activityA.startActivityForResult(intent, RC_B);
然后在活动B中覆盖onFinish()和onFinish
@Override
public void finish() {
Intent resultIntent = new Intent();
resultIntent.putExtra("total", 45); // For Example.
setResult(RESULT_OK, resultIntent);
super.finish();
}
然后在活动A中覆盖onActivityResult并输入如下代码。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == RC_B) {
// get your value of sum from intent
total = intent.getIntExtra("total",0);
}
}
答案 1 :(得分:2)
将您的金额值存储在Sharedpreference中。每次返回活动A时,总结首选项的值。
答案 2 :(得分:1)
使变量和静态
public static double sum =0;
而不是随时随地添加你想要的应用程序和 只需在onActivityResult中显示,无需通过意图(确保在使用后重新初始化)
答案 3 :(得分:0)
要解决加分问题,只需将=+
更改为+=