根据用户输入更改按钮行为

mat*_*ttd 1 java android converter android-edittext android-button

我正在Android中编写一个简单的应用程序.

我遇到过这个问题:我有两个EditText和一个Button.一个EditText的值必须是另一个EditText的倍数.

当用户在第一个EditText中插入一个值然后按下按钮时,另一个EditText应该显示用用户输入计算的值.这在其他经文中也应该是可能的.

像一个简单的单位转换器.当我value1在EditText1中插入并按转换时,应用程序必须在EditText2中显示转换后的值,但如果我value2在EditText2中插入一个并按下转换按钮,应用程序必须在EditText1中显示转换后的值.我的问题是:如何识别最后一个用户输入的EditText?

public void convert(View view) {
    EditText textInEuro = (EditText) findViewById(R.id.euroNumber);
    EditText textInDollar = (EditText) findViewById(R.id.dollarNumber);
    if (toDollar) {
        String valueInEuro = textInEuro.getText().toString();
        float numberInEuro = Float.parseFloat(valueInEuro);
        // Here the conversione between the two currents
        float convertedToDollar = unit * numberInEuro;
        // set the relative value in dollars
        textInDollar.setText(Float.toString(convertedToDollar));
    }

    if (toEuro) {
        String valueInDollar = textInDollar.getText().toString();
        float numberInDollar = Float.parseFloat(valueInDollar);
        //Here the conversione between the two currents
        float convertedToEuro = numberInDollar / unit;
        //set the relative value in dollars
        textInEuro.setText(Float.toString(convertedToEuro));
    }
}
Run Code Online (Sandbox Code Playgroud)

这是编写的代码.我认为使用OnClickListener ..但它不是一个好主意..

abe*_*ker 5

您可以将TextWatcher添加到两个EditText中,以便知道最后一个已更新的文本.

public class MainActivity extends Activity {

EditText dollar;
EditText euro;

private static final int EURO = 0;
private static final int DOLLAR = 1;

private int lastUpdated = DOLLAR;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    dollar = findViewById(R.id.dollar);
    euro = findViewById(R.id.euro);

    dollar.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            lastUpdated = DOLLAR;

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    euro.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            lastUpdated = EURO;

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

}

public void convert(View view) {
    switch (lastUpdated) {
    case EURO:
        //Do work for euro to dollar
        break;
    case DOLLAR:
        //Do work for dollar to euro
        break;
    default:
        break;
    }
}
}
Run Code Online (Sandbox Code Playgroud)