1

There is an EditText on the activity, I click on that EditText, and the input method pops up. Then

  1. I press on the back button, the onBackPressed method defined in the activity is not called, but the input method is hidden now.
  2. I press on the back button again, the onBackPressed method is called this time.

My question is, why is onBackPressed method not called for the first time? And how can I make it work?

Here is my code.

MainActivity.java

package com.dict.androidtest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onBackPressed() {
        Log.d("AndroidTest", "onBackPressed");
        super.onBackPressed();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:id="@+id/activityMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
4

2 回答 2

4

您可以为它添加一个覆盖 textfieldAction 侦听器,如下所示

textEditField = findViewById(android.R.id.editText )
textEditField.setOnEditorActionListener(new TextView.OnEditorActionListener() { 
    @Override 
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) { 
        if (actionId == EditorInfo.IME_ACTION_DONE) { 
           onBackPressed();
           return true;
        } 
        return false; 
    } 
}); 
于 2018-12-16T14:30:54.957 回答
3

EditText 有它自己的侦听器和在编辑窗口处于活动状态时响应的后按方法。onBackPressed() 方法在活动本身直接监听点击时起作用。

于 2018-12-16T14:55:04.597 回答