Отключить автофокус при редактировании текста
У меня есть текст редактирования:
<LinearLayout android:id="@+id/linearLayout7" android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="1" android:id="@+id/editText1" android:text="3">
<requestFocus></requestFocus>
</EditText>
<Button android:text="Button" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/button2"></Button>
</LinearLayout>
а затем некоторые другие вещи под
Проблема, с которой я сталкиваюсь, заключается в том, что сразу, когда приложение начинает фокусироваться на входе, я не хочу, чтобы фокус находился на входе сразу, когда приложение запускается.
Я попытался удалить
<requestFocus></requestFocus>
и ничего не сделал.
Ответы
Ответ 1
Добавьте android:focusable="true"
и android:focusableInTouchMode="true"
в родительский макет EditText следующим образом;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout7" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="true" android:focusableInTouchMode="true">
Я думаю, это должно помочь вам.
Ответ 2
NO Больше работы... просто добавьте android: windowSoftInputMode = "stateAlwaysHidden"
к тегу активности файла Manifest.xml.
Ответ 3
Если вы хотите очистить фокус по умолчанию для редактируемого текста, используйте следующие 2 атрибута
android:focusable="false"
android:focusableInTouchMode="true"
внутри родительского линейного макета.
например:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="true"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email id"
android:inputType="textEmailAddress"
android:maxLines="1"
/>
</LinearLayout>
Если вы хотите скрыть клавиатуру при создании активности, используйте эти атрибуты внутри тега активности файла манифеста, например:
<activity
android:configChanges="screenSize|orientation|keyboardHidden"
android:screenOrientation="portrait"
android:name=".activities.LoginActivity"
android:windowSoftInputMode="stateHidden|adjustResize"/>
Если вы хотите скрыть клавиатуру при нажатии кнопки или при возникновении какого-либо события, используйте следующий код
public void onClick(View v) {
try {
//InputMethodManager is used to hide the virtual keyboard from the user after finishing the user input
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isAcceptingText()) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
} catch (NullPointerException e) {
Log.e("Exception", e.getMessage() + ">>");
}
}
} catch (NullPointerException e) {
Log.e("Exception", e.getMessage() + ">>");
}
Если вы хотите снять фокус с редактирования текстовых полей после выхода из упражнения
@Override
protected void onResume() {
super.onResume();
mEmail.clearFocus();
mPassword.clearFocus();
}
И, наконец, если вы хотите очистить данные в текстовых полях редактирования при отправке формы, используйте
@Override
protected void onResume() {
super.onResume();
mEmail.getText().clear();
mPassword.getText().clear();
}
Ответ 4
<LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="0px"
android:layout_height="0px" />
<EditText android:text=""
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/hint">
</EditText>
Никакой другой кодировки не требуется, это простое и ясное решение.
Ответ 5
Вы можете использовать скрытый оконный режим ввода для скрытия клавиатуры и android:focusable="false"
и android:focusableInTouchMode="true"
<activity
android:name=".MainActivity"
android:windowSoftInputMode="stateHidden"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Ответ 6
<EditText
android:id="@+id/input"
android:layout_width="0dp"
android:layout_height="48dp"
android:focusable="false"
android:focusableInTouchMode="false" />
detailInputView = (EditText) debugToolsView.findViewById(R.id.input);
detailInputView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
detailInputView.setFocusable(true);
detailInputView.setFocusableInTouchMode(true);
return false;
}
});
Ответ 7
Просто добавьте следующее в свой основной тег xml тега:
android:focusableInTouchMode="true"
Ответ 8
Hei Lee,
Есть несколько способов сделать это, Mudassir дает вам возможность сделать это.
Если идея не работает, тогда сделайте простое дело -
В вашем AndroidManifest>Activity
добавить этот простой код:
android:windowSoftInputMode="stateHidden"
Ничего не нужно делать в EditText в XML, все будет работать, и фокус не появится.
Посмотрите пример кода реальной жизни:
<activity
android:name=".MainActivity"
android:windowSoftInputMode="stateHidden"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Ответ 9
попробуйте этот код в LinearLayout
<LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:hint="Search..."
android:drawableRight="@drawable/ic_search"
android:id="@+id/search_tab_hotbird_F"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recyHotbird_F"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Ответ 10
У меня это сработало, желание тоже поможет вам.
Или :
android:windowSoftInputMode="stateAlwaysHidden"
добавьте это свойство в свой файл Manifest.xml под конкретным действием, в котором вы хотите отключить автофокус. Минусы: он будет скрывать только вашу мягкую клавиатуру, курсор будет все еще там.
Остальное:
android:focusableInTouchMode="true"
добавьте это свойство в ваш XML файл пользовательского интерфейса (в родительском макете), чтобы оно скрывало фокус и клавиатуру.
Ответ 11
для очистки по умолчанию requestFocuse вы должны установить свой View parent focusable = "true", как показано ниже
<android.support.constraint.ConstraintLayout
android:id="@+id/coordinatorChild"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true">