我要做的是用每个键事件更新TextView - 基本上将EditText的内容复制到TextView。出于某种原因,它不起作用。这是代码:
View.OnKeyListener keyHandler = new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
TextView id = (TextView)findViewById(R.id.previewEmplIdData);
TextView fn = (TextView)findViewById(R.id.previewNameData);
TextView ttl = (TextView)findViewById(R.id.previewTitleData);
TextView mgr = (TextView)findViewById(R.id.previewMgrData);
TextView loc = (TextView)findViewById(R.id.previewLocData);
TextView strt = (TextView)findViewById(R.id.previewStartData);
String text = "";
EditText et;
switch(v.getId()){
case R.id.etFirstName:
et = (EditText)v; // must first switch to a text field
text = et.getText().toString();
fn.setText(text);
break;
case R.id.etLastName:
et = (EditText)v;
text = et.getText().toString();
break;
case R.id.etEmplId:
et = (EditText)v;
text = et.getText().toString();
id.setText(text);
break;
case R.id.etStartDate:
et = (EditText)v;
text = et.getText().toString();
strt.setText(text);
break;
case R.id.etTitle:
et = (EditText)v;
text = et.getText().toString();
ttl.setText(text);
break;
case R.id.spinnerLocation:
break;
case R.id.spinnerManager:
break;
}
return false;
}
};
基本上我在按键时切换View ID,然后将视图转换为EditText。我不确定为什么这不起作用...我总是非常不幸的是让switch语句工作。有什么帮助吗?
答案 0 :(得分:2)
你在哪里应用keyHandler
?如果您刚刚创建并初始化它,但未在任何视图中使用,则根本不会运行。
答案 1 :(得分:2)
OnKeyListener不适用于软键盘。您应该实施TextWatcher来跟踪文本更改。另请查看here。
答案 2 :(得分:0)
我刚刚使用以下方法解决了同样的问题:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
public class InputField extends AppCompatActivity {
private EditText input;
private TextView displayString;
private String writeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_field);
input = (EditText) findViewById(R.id.editText);
displayString = (TextView) findViewById(R.id.displayStringText);
input.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) {
writeText = input.getText().toString();
displayString.setText(writeText);
}
});
}
}