我想知道如何将 convert_and_multiply 方法中的字符串参数传递给 findViewById 方法,使字符串成为方法调用的一部分,而不再是 String。例如,我想传递参数“fruit_1_price”,使其变为 findViewById(R.id.fruit_1_price);
我正在阅读有关 Java 中的“反射”的内容,但我无法完全理解它,以及它是否适用于我的情况。我也尝试过使用字符串通配符和占位符,但我无法理解如何创建一个字符串,而不是一个字符串。
感谢您的帮助。
@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;
}
最佳答案
将您的方法更改为此代码:
public double convert_and_multiply(String v, String s) {
Resources res = getResources();
int id1 = res.getIdentifier(v, "id", getContext().getPackageName());
TextView price = findViewById(id1);
int id2 = res.getIdentifier(s, "id", getContext().getPackageName());
Spinner amount = findViewById(id2);
Double total = Double.valueOf(amount.getSelectedItem().toString()) * Double.parseDouble(price.getText().toString());
return total;
}
关于java - 如何传递 String 参数使其成为类方法调用的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52416091/