如何即时更新货币转换器的输入?

时间:2011-12-07 20:58:28

标签: android android-widget

好的,所以我试图根据我在网上找到的教程在美元和欧元之间制作货币转换器。问题是该教程依靠2个单选按钮在转换之间切换,参考命令说明程序首先调用哪个方法。我希望程序能够从两个单选按钮中立即进行转换,例如,如果我在欧元或美元editText视图中写一个数字...然后点击转换按钮将进行适当的转换。但我不能,因为有两种方法,除非有一种方法同时显示他们的输入它将无法工作。所以我的问题是如何我按下转换时同时更新两个editText视图按钮?谢谢

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ConvertorActivity extends Activity {
    TextView dollars;
    TextView euros;

    Button convert;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        dollars = (TextView)this.findViewById(R.id.dollars);
        euros = (TextView)this.findViewById(R.id.euros);



        convert = (Button)this.findViewById(R.id.convert);

        convert.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                convertBoth();

            }
        });
    }

    public void convertBoth(){
        convertDollarsToEuros();
        convertEurosToDollars();
    }
    protected void convertDollarsToEuros() {
        double val = Double.parseDouble(dollars.getText().toString());
        // in a real app, we'd get this off the 'net
        euros.setText(Double.toString(val*0.67));
    }

    protected void convertEurosToDollars() {
        double val = Double.parseDouble(euros.getText().toString());
        // in a real app, we'd get this off the 'net
        dollars.setText(Double.toString(val/0.67));
    }
}

1 个答案:

答案 0 :(得分:1)

我认为你想要的是:

  • 如果用户更改了美元金额,请将其转换为欧元
  • 如果用户更改了欧元金额,请将其转换为美元

如果是这种情况,您可以添加成员变量mLastEditedViewId并使用TextWatcher来跟踪上次更改的字段。然后,onClick,相应地致电convertDollarsToEuros()convertEurosToDollars

onCreate

  dollars.addTextChangedListener(new MyTextWatcher(dollars));
  euros.addTextChangedListener(new MyTextWatcher(euros));

  convert.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
      switch (mLastEditedViewId) {
      case R.id.dollars:
        convertDollarsToEuros();
        break;
      case R.id.euros:
        convertEurosToDollars();
        break;
      }
    }
  });

定义TextWatcher的内部类:

private class MyTextWatcher implements TextWatcher {
  private int mTextViewId;
  public MyTextWatcher(TextView view) {
    mTextViewId = view.getId();
  }
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  }
  public void onTextChanged(CharSequence s, int start, int before, int count) {
    mLastEditedViewId = mTextViewId;
  }
  public void afterTextChanged(Editable s) {
  }
}