Search code examples
javaandroidandroid-background

how to operate on data recorded from edit text


I want to take the depth input by the user and mathematically operate on it to obtain cost and then display it to the user. How do I go about doing that?(If didn't notice already, I don't know Java). Thanks.

 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);
    }

Solution

  • You can create a button to obtain the value. For example:

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

    Then you can catch the click event (put it inside onCreate method):

    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));
            }
    });
    

    Good luck!