События на EditText вообще не запускаются - PullRequest
0 голосов
/ 30 октября 2019

У меня есть EditText, и я хочу поймать событие, когда пользователь использует «Готово» или «Ввод». В настоящее время я тестирую на эмуляторе с Pixel API 26

. Я перепробовал множество решений, найденных в StackOverFlow, таких как добавление setSingleLine или редактирование XML с помощью

android:singleLine="true"
android:inputType="text"
android:maxLines="1""

, но ничего не работает. Я действительно не знаю, в чем проблема.

Это XML:

<EditText
    android:id="@+id/input_search"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerVertical="true"
    android:layout_toEndOf="@+id/ic_magnify"
    android:background="@null"
    android:hint="Enter Address, City or Zip Code"
    android:imeOptions="actionGo|actionSearch|actionNext|actionSend"
    android:singleLine="true"
    android:inputType="text"
    android:maxLines="1"
    android:textColor="#000"
    android:textSize="15sp" /> 

В моем классе MapFragment я получаю ссылку на EditBox внутри "onCreateView"function:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View v = inflater.inflate(R.layout.activity_maps, container,
                false);

    mSearchText = v.findViewById(R.id.input_search);
    mSearchText.setSingleLine();
    init();

    // Hiding the action bar
    ((AppCompatActivity) getActivity()).getSupportActionBar().hide();

    return v;
}

и затем в функции "init" я делаю это:

private void init() {

    Log.d("Yolo2", "Before");

    //Search field
    mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if(actionId == EditorInfo.IME_ACTION_SEARCH
                || actionId == EditorInfo.IME_ACTION_DONE
                || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
                    Log.d("Yolo2", "Yes");
                    //execute our method for searching
                    geoLocate();
                }

            Log.d("Yolo2", "No");
            return false;
        }
    });
}

Я перепробовал много других событий, и ни одно из них не сработало. Я ничего не получаю от журналов отладки. Я пытался отследить события смены ключа и набрать ключ внутри EditText.

Ответы [ 4 ]

0 голосов
/ 03 ноября 2019

Спасибо всем за помощь в решении этой проблемы. Я сделал ошибку, используя этот код в классе MapFragment, когда я должен был использовать его в MapActivity. Мой код теперь работает отлично, и все ваши ответы, вероятно, тоже правильные.

0 голосов
/ 30 октября 2019

Попробуйте с android:imeOptions="actionDone" и проверьте с помощью приведенного ниже кода. Сначала ручка KeyEvent, а затем action.

mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (keyEvent != null && keyEvent.getAction() != KeyEvent.ACTION_DOWN)
            return false;

        if(actionId == EditorInfo.IME_ACTION_DONE
            || actionId == EditorInfo.IME_NULL) {
                Log.d("Yolo2", "Yes");
                //execute our method for searching
                geoLocate();
        }

        Log.d("Yolo2", "No");
        return false;
    }
});
0 голосов
/ 30 октября 2019

Пожалуйста, попробуйте это

    mSearchText = v.findViewById(R.id.input_search);
mSearchText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            geoLocate();
            handled = true;
        }
        return handled;
    }
});
0 голосов
/ 30 октября 2019

Удалите условие if и попробуйте

 mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            geoLocate();
            return true;
        }
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...