java - 如何传递 String 参数使其成为类方法调用的一部分?

标签 java android

我想知道如何将 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/

相关文章:

java - 使用 Java 反射处理事件

java - 创建文件和目录无法正常工作

java - <MVC :annotation-driven/> with un-annotated controllers

android - 无法在 Ubuntu 上启动 uiautomatorviewer

java - Android Socket 将对象转换为ArrayList

android - librart.so 中的 native 崩溃,全部在 Android 8.0 上,缺少符号

android - 要求在应用 list 中提及 Google Play 服务版本

java - ASCII 码 => 字符串

android - 是否可以在 Android Oreo 上更改通知点的颜色

java - 为什么本地类接受静态最终变量?