我希望用户输入分钟和秒钟的时间。在输入分钟后如何自动添加“:”?
将Eclipse与Java结合使用。
到目前为止,我有这个:
EditText editTextT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextT = (EditText) findViewById(R.id.editTextT);
editTextT.setOnKeyListener(new EditText.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (editTextT.getText().length() == 2) {
editTextT.setText(editTextT.getText() + ":");
editTextT.setSelection(editTextT.getText().length());
}
return false;
}
});
答案 0 :(得分:0)
您必须向KeyListener
添加TextField
。
然后,例如,您可以对释放的密钥作出反应。您可以检查textarea中的文本长度,然后在字符串的末尾添加:
看看这个:
textfield.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if (textfield.getText().length() == 2) {
textfield.setText(textfield.getText() + ":");
textfield.setCaretPosition(textfield.getText().length());
}
}
});
修改强>
如上所述,这是Java的解决方案,如果你需要Android解决方案(因为你的editText
),试试这个:
edittext.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable s) {
if (editText.getText().length() == 2) {
editText.setText(editText.getText() + ":");
editText.setSelection(et.getText().length());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
}
编辑2:请参阅更新并使用TextWatcher进行尝试。