我想知道如何将convert_and_multiply方法中的字符串参数传递给findViewById方法,以便该字符串成为方法调用的一部分,而不再是String。例如,我想传递参数“ fruit_1_price”,使其变为findViewById(R.id.fruit_1_price);。
我在阅读有关Java中的“反射”的信息,但我不能完全理解它,以及它是否适用于我的情况。我也尝试过使用String通配符和占位符,但是我不明白如何制作String,而不是String。
感谢您的任何帮助。
@Override
public void onClick(View view) {
Double fruit_1_total = convert_and_multiply("fruit_1_price", "fruit_1_spinner");//, fruit_2_total, fruit_3_total;
Toast.makeText(c, Double.toString(fruit_1_total),Toast.LENGTH_LONG).show();
}
public double convert_and_multiply(String v, String s) {
TextView price = findViewById(R.id.v);
Spinner amount = findViewById(R.id.s);
Double total = Double.valueOf(amount.getSelectedItem().toString()) * Double.parseDouble(price.getText().toString());
return total;
}
为什么要使它复杂化?将ID直接传递给convert_and_multiply函数:
@Override
public void onClick(View view) {
Double fruit_1_total = convert_and_multiply(R.id.v, R.id.s);//, fruit_2_total, fruit_3_total;
Toast.makeText(c, Double.toString(fruit_1_total),Toast.LENGTH_LONG).show();
}
public double convert_and_multiply(int priceId, int amtId) {
TextView price = findViewById(priceId);
Spinner amount = findViewById(amtId);
Double total = Double.valueOf(amount.getSelectedItem().toString()) * Double.parseDouble(price.getText().toString());
return total;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句