我阅读了有关如何设置要聚焦的对象的问题,但我似乎找不到我想要做的事情的答案。
使用 On Focus Listener 我完成了以下操作:
Ehour.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if (!arg1) {
if (Ehour.getText().length()<=0) {
Toast.makeText(getApplicationContext(), "No Hour Entered", Toast.LENGTH_LONG).show();
Calendar nohour = Calendar.getInstance();
Ehour.setText(numberformatter(nohour.get(Calendar.HOUR_OF_DAY)));
Ehour.setFocusable(true);
Ehour.requestFocus();
}
}
}});
我已经尝试过以下帖子中的建议:
我读了这篇文章,但使用这些建议似乎也不起作用:创建和显示布局时如何将焦点设置在视图上?
我的目标是,当编辑文本焦点丢失时,如果给定的条目无效,我需要移回该焦点。
此外,根据 Bill Mote 给出的建议,我也尝试过:
Ehour.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if (!arg1) {
if (Ehour.getText().length()<=0) {
Toast.makeText(getApplicationContext(), "No Hour Entered", Toast.LENGTH_LONG).show();
Calendar nohour = Calendar.getInstance();
Ehour.setText(numberformatter(nohour.get(Calendar.HOUR_OF_DAY)));
((EditText)arg0).requestFocus();
}
}
}});
** 编辑 **
我什至在 requestFocus() 之前添加了以下行:
((EditText)arg0).setFocusable(true);
*** 编辑 ****
从这篇文章尝试过:阻止 EditText 在 Activity 启动时获得焦点
以下变化:
在第一个布局标题的布局中,我添加了:
android:id="@+id/enterdata"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
然后在 OnChange FocusListener 中我这样做了:
Ehour.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if (!arg1) {
if (((EditText)arg0).getText().length()<=0) {
Toast.makeText(getApplicationContext(), "No Hour Entered", Toast.LENGTH_LONG).show();
Calendar nohour = Calendar.getInstance();
((EditText)arg0).setText(numberformatter(nohour.get(Calendar.HOUR_OF_DAY)));
findViewById(R.id.enterdata).requestFocus();
((EditText)arg0).setFocusable(true);
((EditText)arg0).setFocusableInTouchMode(true);
((EditText)arg0).requestFocus();
}
}
}});
但是,我仍然得到与以前相同的行为,焦点所在的编辑文本保持这种方式,但我希望焦点所在的编辑文本看起来已聚焦,但它似乎无法使用,就好像它仍在等待一样专注。
*** 编辑 ****
根据最近在 stackoverflow 上找到的帖子,下面的代码中提出问题的用户遇到了与我相同的问题:
Ehour.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if (!arg1) {
if (((EditText)arg0).getText().length()<=0) {
Calendar nohour = Calendar.getInstance();
((EditText)arg0).setText(numberformatter(nohour.get(Calendar.HOUR_OF_DAY)));
if (((EditText)arg0).requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Emin.clearFocus();
Toast.makeText(getApplicationContext(), "No Hour Entered", Toast.LENGTH_LONG).show();
}
}
}
}});