Перейдите к другому EditText, когда Soft Keyboard Next будет нажата на Android
Когда я нажимаю "Далее", фокус на пользовательском EditText должен быть перемещен в пароль. Затем, из пароля, он должен двигаться вправо и так далее. Можете ли вы помочь мне в том, как его кодировать?
![enter image description here]()
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name*" />
<EditText
android:id="@+id/txt_User"
android:layout_width="290dp"
android:layout_height="33dp"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:id="@+id/LinearLayout02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password*" />
<EditText
android:id="@+id/txt_Password"
android:layout_width="290dp"
android:layout_height="33dp"
android:singleLine="true"
android:password="true" />
<TextView
android:id="@+id/confirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password*" />
<EditText
android:id="@+id/txt_Confirm"
android:layout_width="290dp"
android:layout_height="33dp"
android:singleLine="true"
android:password="true" />
</LinearLayout>
Ответы
Ответ 1
Обработка фокуса
Движение фокуса основано на алгоритме, который находит ближайший
сосед в заданном направлении. В редких случаях алгоритм по умолчанию может не соответствовать предполагаемому поведению разработчика.
Измените поведение поведенческой навигации по умолчанию, используя следующие атрибуты XML:
android:nextFocusDown="@+id/.."
android:nextFocusLeft="@+id/.."
android:nextFocusRight="@+id/.."
android:nextFocusUp="@+id/.."
Помимо направленной навигации вы можете использовать навигацию по вкладкам. Для этого вам нужно использовать
android:nextFocusForward="@+id/.."
Чтобы получить конкретное представление для фокусировки, вызовите
view.requestFocus()
Для прослушивания определенных изменений фокусных событий используйте View.OnFocusChangeListener
Клавиатура
Вы можете использовать android:imeOptions
для обработки этой дополнительной кнопки на клавиатуре.
Дополнительные возможности, которые вы можете включить в IME, связанном с редактором для улучшения интеграции с вашим приложением. Константы здесь соответствуют тем, которые определены imeOptions.
Константы imeOptions включают в себя множество действий и флагов, см. ссылку выше для своих значений.
Пример значения
ActionNext:
клавиша действия выполняет "следующую" операцию, заставляя пользователя следующее поле, которое примет текст.
ActionDone:
клавиша действия выполняет операцию "done", что обычно означает, что вводить нечего и IME будет закрыт.
Пример кода:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="32dp"
android:layout_marginTop="16dp"
android:imeOptions="actionNext"
android:maxLines="1"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="24dp"
android:imeOptions="actionDone"
android:maxLines="1"
android:ems="10" />
</RelativeLayout>
Если вы хотите прослушать события, связанные с ошибками, используйте TextView.OnEditorActionListener
.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
Ответ 2
android:inputType="text"
должен принести тот же эффект. После того, как вы нажмете рядом, чтобы перейти к следующему элементу.
android:nextFocusDown="@+id/.."
используйте это в добавлении, если вы не хотите, чтобы следующее представление получило фокус
Ответ 3
добавить свой editText
android:imeOptions="actionNext"
android:singleLine="true"
добавить свойство к активности в манифесте
android:windowSoftInputMode="adjustResize|stateHidden"
в файле макета ScrollView устанавливается как корень или родительский макет все ui
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ukuya.marketplace.activity.SignInActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--your items-->
</ScrollView>
</LinearLayout>
, если вы не хотите, чтобы каждый раз, когда он добавлялся, создайте стиль:
добавить стиль в значения /style.xml
по умолчанию/стиль:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="editTextStyle">@style/AppTheme.CustomEditText</item>
</style>
<style name="AppTheme.CustomEditText" parent="android:style/Widget.EditText">
//...
<item name="android:imeOptions">actionNext</item>
<item name="android:singleLine">true</item>
</style>
Ответ 4
Используйте следующую строку
android:nextFocusDown="@+id/parentedit"
parentedit
- это идентификатор следующего EditText
на который нужно сфокусироваться.
В приведенной выше строке также потребуется следующая строка.
android:inputType="text"
или же
android:inputType="number"
Спасибо за предложение @Алексей Хлебников.
Ответ 5
android:inputType="textNoSuggestions"
android:imeOptions="actionNext"
android:singleLine="true"
android:nextFocusForward="@+id/.."
Добавление дополнительного поля
Android: inputType = "textNoSuggestions"
работал в моем случае!
Ответ 6
В обработчике onEditorAction имейте в виду, что вы должны вернуть логическое значение, указывающее, обрабатываете ли вы действие (true), или если вы применили некоторую логику и хотите нормальное поведение (false), как в следующем примере:
EditText te = ...
te.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event){
if (actionId == EditorInfo.IME_ACTION_NEXT) {
// Some logic here.
return true; // Focus will do whatever you put in the logic.
}
return false; // Focus will change according to the actionId
}
});
Я нашел это, когда вернул true после выполнения моей логики, так как фокус не двигался.
Ответ 7
<AutoCompleteTextView
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/user"
android:hint="@string/username"
android:inputType="text"
android:maxLines="1"
android:imeOptions="actionNext"
android:singleLine="true" />
Эти три строки делают волшебство
android:maxLines="1"
android:imeOptions="actionNext"
android:singleLine="true"
Ответ 8
просто используйте следующий код, он будет работать нормально и будет использовать inputType для каждого edittext, а следующая кнопка появится на клавиатуре.
android:inputType="text" or android:inputType="number" etc
Ответ 9
В некоторых случаях вам может понадобиться переместить фокус на следующее поле вручную:
focusSearch(FOCUS_DOWN).requestFocus();
Это может понадобиться, если, например, у вас есть текстовое поле, в котором при щелчке открывается средство выбора даты, и вы хотите, чтобы фокус автоматически перемещался в следующее поле ввода после выбора пользователем даты и закрытия средства выбора. Нет никакого способа справиться с этим в XML, это должно быть сделано программно.
Ответ 10
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="666dp"
android:background="#1500FFe5"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editGrWt"
android:layout_marginTop="14dp"
android:layout_toLeftOf="@+id/textView3"
android:ems="6"
android:text=" Diamond :"
android:textColor="@color/background_material_dark"
android:textSize="15sp" />
<EditText
android:id="@+id/editDWt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/TextView02"
android:layout_alignLeft="@+id/editGrWt"
android:background="@color/bright_foreground_inverse_material_light"
android:ems="4"
android:hint="Weight"
android:inputType="numberDecimal"
android:nextFocusLeft="@+id/editDRate"
android:selectAllOnFocus="true"
android:imeOptions="actionNext"
/>
<requestFocus />
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/TextView02"
android:layout_below="@+id/TextView02"
android:layout_marginTop="14dp"
android:ems="6"
android:text=" Diamond :"
android:textColor="@color/background_material_dark"
android:textSize="15sp" />
<EditText
android:id="@+id/editDWt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/TextView03"
android:layout_alignBottom="@+id/TextView03"
android:layout_alignLeft="@+id/editDWt"
android:background="@color/bright_foreground_inverse_material_light"
android:ems="4"
android:hint="Weight"
android:inputType="numberDecimal"
android:text="0"
android:selectAllOnFocus="true"
android:imeOptions="actionNext"/>
<requestFocus />
<TextView
android:id="@+id/TextView04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editDWt1"
android:layout_marginTop="14dp"
android:layout_toLeftOf="@+id/textView3"
android:ems="6"
android:text=" Stone :"
android:textColor="@color/background_material_dark"
android:textSize="15sp" />
<EditText
android:id="@+id/editStWt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/TextView04"
android:layout_alignBottom="@+id/TextView04"
android:layout_alignLeft="@+id/editDWt1"
android:background="@color/bright_foreground_inverse_material_light"
android:ems="4"
android:hint="Weight"
android:inputType="numberDecimal"
android:nextFocusForward="@+id/editStRate1"
android:imeOptions="actionNext" />
<requestFocus />
<TextView
android:id="@+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/TextView04"
android:layout_below="@+id/editStRate1"
android:layout_marginTop="14dp"
android:ems="6"
android:text=" Stone :"
android:textColor="@color/background_material_dark"
android:textSize="15sp" />
</RelativeLayout>
</ScrollView>
Ответ 11
Если вы хотите использовать многострочный EditText
с imeOptions
, попробуйте:
android:inputType="textImeMultiLine"
Ответ 12
Добавьте inputType к тексту редактирования и при вводе он перейдет к следующему тексту редактирования
android:inputType="text"
android:inputType="textEmailAddress"
android:inputType="textPassword"
и многое другое.
inputType = textMultiLine не переходит к следующему тексту редактирования при вводе
Ответ 13
Inside Edittext just arrange like this
<EditText
android:id="@+id/editStWt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:imeOptions="actionNext" //now its going to rightside/next field automatically
..........
.......
</EditText>
Ответ 14
Простой способ, когда у вас есть только несколько полей одно за другим:
Нужно установить
android:maxLines="1"
android:imeOptions="actionNext"
android:inputType=""
<- Укажите тип текста, в android:inputType=""
случае он будет многострочным и будет препятствовать android:inputType=""
Образец:
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/text_large"
android:maxLines="1"
android:inputType="textEmailAddress"
android:imeOptions="actionNext"
android:layout_marginLeft="@dimen/element_margin_large"
android:layout_marginRight="@dimen/element_margin_large"
android:layout_marginTop="0dp"/>