we got homework to make convertor of weights where the fields are updated while typing the number (no need to click "calculate" or anything). one of the students offered the code below. the code works: when putting a number in field 1, field 2 changes while typing.
what i dont understand is how does that work?
in the onKey
method, no value is given to View
int
and keyEvent
so how does the listener "knows" on which view to and what keys to listen to or what event to activate ?
public class Screen extends Activity {
double weight = 2.20462;
EditText kgEdit, lbsEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kgEdit = (EditText) findViewById(R.id.kgEdit);
lbsEdit = (EditText) findViewById(R.id.lbsEdit);
kgEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String kg = kgEdit.getText().toString();
if (kg.isEmpty()) {
lbsEdit.setText("");
} else {
double num = Double.valueOf(kgEdit.getText().toString()) * weight;
lbsEdit.setText(num + "");
}
return false;
}
});
lbsEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String lbs = lbsEdit.getText().toString();
if (lbs.isEmpty()) {
kgEdit.setText("");
} else {
double num = Double.valueOf(lbsEdit.getText().toString()) / weight;
kgEdit.setText(num + "");
}
return false;
}
});
}
}
答案 0 :(得分:2)
我将专注于其中一个文本字段来回答这个问题。看看第一行:
kgEdit = (EditText) findViewById(R.id.kgEdit);
所有这一切都是为了输入kg而引用EditText
。现在有一个引用,我们可以调用该对象的方法。
接下来,我们有了这个:
kgEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// ...
}
}
以上内容如下。参考我们在第一行中检索到的公斤EditText
。方法setOnKeyListener
执行以下操作(来自here):"注册在此视图中按下硬件键时要调用的回调。"
这意味着您现在已经告诉该视图,每当用户按下某个键时,您希望得到通知,而此EditText具有焦点。您调用Android API,在后台Android处理您要求的所有内容。它会使用View view
,int keyCode
和KeyEvent event
调用该方法。你给它一个方法,然后处理这些输入。所以你的代码中没有任何地方你需要调用这个方法,Android会在后台调用它,你永远不会看到或担心它。
现在,因为您在kgEdit
上调用了该方法,这意味着只有在kgEdit
被聚焦并键入键时才会调用以下代码,因此不会与其他代码混淆EditText
。它稍后会在下面获得自己的方法调用。这是setOnKeyListener
中的其余代码:
String kg = kgEdit.getText().toString();
if (kg.isEmpty()) {
lbsEdit.setText("");
} else {
double num = Double.valueOf(kgEdit.getText().toString()) * weight;
lbsEdit.setText(num + "");
}
return false;
这样做的目的是获取kgEdit
中的当前文本,该文本已使用用户按下的键进行了更新。它只检查文本是否为空,如果是,则删除lbsEdit
中的文本。如果它不为空,则获取文本,将其转换为数字,将数字从kg转换为lbs并更新lbsEdit
答案 1 :(得分:0)
You have to use addTextChangedListener like this-
EditText editText = (EditText) findViewById(R.id.editText1);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
//do here your calculation
String data = s.toString();
}
});