简体   繁体   中英

What happens after my button does its job? (ANDROID)

So I created a basic converter app that converts miles to kilometer. In the app, the user can either enter values on the miles edittext or kilometers edittext. After entering a value and pressing on the "convert" button, the value is converted and displayed accordingly. What I really wanted to do is remove the convert button so that the conversion is done as the user is enter the input simultaneously. I did some research and found out about textlistener but failed miserably in implementing it.

So i thought of keeping the button, and going on a different route. What i'm trying to do is for example, if the user first enters value on the miles edit text and converts it to kms. Then when the user presses on the kilometers edit text, I want the edit text on both miles and kilometers to be blank so that the user doesnt have to keep erasing the values.

I thought about this a lot. I can do it, but I'm confused about where to put the code, since there is only one method that I created, ie convertLength().

I am thoroughly confused, so any help would be greatly appreciated. :)

package com.abhinavbhatta.converter;
import android.os.Bundle;
public class ConvertLength extends Activity {
    Button clength;
    EditText mi;
    EditText km;

    double milesValue;
    double kmValue;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_convert_length);

}       


public void convertLength(View view){
    clength = (Button) findViewById(R.id.clength);

    mi = (EditText) findViewById(R.id.et_mi);
    km = (EditText) findViewById(R.id.et_km);       

    Intent intentLength = getIntent();

    if (mi.isFocused()){

        milesValue = Double.parseDouble(mi.getText().toString());
        kmValue = milesValue * 1.6;
        km.setText( String.format( "%.2f", kmValue ) );


    }

    if (km.isFocused()){
        kmValue = Double.parseDouble(km.getText().toString());
        milesValue = kmValue/(1.6);
        mi.setText( String.format( "%.2f", milesValue ) );      

    }

}



public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.convert_length, menu);
    return true;
}

}

I think you can use a TextWatcher to do some dynamic action.

Read this other answer to find out more. :)

need EditText with readonly indent

Can you post which code you are using for resetting the values...or you can try this :

EditText edit;
edit.setText(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM