我有以下布局:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/others"
android:id="@+id/input_others" />
<EditText
android:minEms="2"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:paddingLeft="@dimen/number_input_padding"
android:paddingRight="@dimen/number_input_padding"
android:id="@+id/input_others_number"
android:text="@string/others_default"/>
</LinearLayout>
如果用户触摸EditText,则应选中该复选框,并删除其值:
final CheckBox othersButton = findViewById(R.id.input_others);
final EditText othersNumber = findViewById(R.id.input_others_number);
othersNumber.setOnFocusChangeListener((view, hasFocus) -> {
if (hasFocus) {
othersButton.setChecked(true);
othersNumber.setText("");
}
});
问题在于,如果我触摸EditText,虽然它会获得焦点(底线颜色变得不同),但键盘不会出现(仅适用于第二次触摸)。但是,如果我删除了行othersNumber.setText("");
,键盘就会出现第一次触摸。
为什么会这样,我该如何解决?我知道我可以强制键盘出现,但我认为这不需要。
答案 0 :(得分:0)
在if(hasFocus)中添加:
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(othersNumber, InputMethodManager.SHOW_FORCED);
所以它看起来像这样:
if (hasFocus) {
othersButton.setChecked(true);
othersNumber.setText("");
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(othersNumber, InputMethodManager.SHOW_FORCED);
}
键盘将在第一次点击时出现。