如何对编辑文本记录的数据进行操作

how to operate on data recorded from edit text

我想把用户输入的depth进行数学运算得到cost然后显示给用户.我该怎么做?(如果还没有注意到,我不知道 Java)。谢谢

 private void estimateCost(View view){
        EditText depth = findViewById(R.id.depth);
        TextView cost = findViewById(R.id.cost);
        String x = depth.getText().toString().trim();
        cost.setText(x);
    }

您需要解析从EditText中获取的String,然后进行一些操作。

 private void estimateCost(View view){
    EditText depth = findViewById(R.id.depth);
    TextView cost = findViewById(R.id.cost);

    String x = depth.getText().toString().trim();  

    // parse to a number, i.e. int
    int depthValue = Integer.parseInt(x);

    // calculate total cost
    int totalCost = ...

    cost.setText(String.valueOf(totalCost));
}

您可以创建一个按钮来获取值。例如:

<Button
        android:id="@+id/bt_calc"
        android:text="calc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

然后就可以捕捉点击事件了(放在onCreate方法里面):

EditText depth = (EditText) findViewById(R.id.depth);
TextView cost = (TextView) findViewById(R.id.cost);
Button btCalc = (Button) findViewById(R.id.bt_calc);
int costValue;

btCalc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //in here you can

            //get the depth from the EditText:
            int depthValue = Integer.valueOf(depth.getText().toString());

            //do the operations (example):
            costValue = depthValue + 1;

            //and display the cost in the TextView:
            cost.setText(String.valueOf(costValue));
        }
});

祝你好运!

如果您的输入也包含字母,您将无法使用 Integer.parseInt()

从中获取 int

使用这个

int x = 0;
for (int i=0; i < str.length(); i++) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') continue;
    x = x * 10 + c - '0';
}