[英]trying to add the sum of two numbers from two different button clicks
imageview burger = 7.99 when clicked, imageview fries = 2.99 when clicked, I want to get the sum of both however when i click one after the other it refreshes and just addeds the value inside instead of adding on to the previous value.单击时 imageview burger = 7.99,单击时 imageview fries = 2.99,我想获得两者的总和,但是当我一个接一个地单击它时,它会刷新并且只是将值添加到内部而不是添加到前一个值。 I feel like the solution is right in front of me but i still have no idea what I am missing here...........
我觉得解决方案就在我面前,但我仍然不知道我在这里错过了什么.......
public class ThirdActivity extends AppCompatActivity {
static double price1 = 0;
static double price2 = 0;
TextView total;
double bill;
static int but1_value = 0;
static int but1_value1 = 0;
ImageView burger;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
TextView tab = (TextView) findViewById(R.id.Table_Size);
burger = (ImageView) findViewById(R.id.burger);
total = (TextView) findViewById(R.id.price1);
final ImageView fries = (ImageView) findViewById(R.id.fries);
fries.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
price2 = price2 + 2.99;
total.setText("Total: " + price2);
}
});
burger.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
price1 = price1 + 7.99;
total.setText("Total: " + price1);
}
});
In your total
you are either setting price1
or price2
.在你的
total
,你要么设置price1
或price2
。
You should set the addition of two, as your goal is.您应该按照您的目标设置两个相加。
total.setText("Total: " + (price1 + price2));
You have assigned a new value to the variable price1
from one place and to price2
from another place.您分配一个新值可变
price1
从一个地方和price2
从另一个地方。
If you want to maintain the value use a single variable and save in it from both places, or directly add them and set the value.如果要维护该值,请使用单个变量并从两个位置保存在其中,或者直接添加它们并设置值。
Use:用:
total.setText("Total: " + (price1+price2));
I may not have understood your problem.我可能没有理解你的问题。 Feel free to clarify it.
随意澄清一下。
The best solution is to create global variable total_price.最好的解决方案是创建全局变量 total_price。
private double total_price = 0;
Update the value of total_price whenever you click on fries每次点击薯条时更新 total_price 的值
total_price += price1
and for burger和汉堡
total_price += price2
and then set total as然后将总计设置为
total.setText("Total: " + total_price);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.