[英]Android: onBackPressed is not called when EditText is focused
活動上有一個EditText,我單擊該EditText,然后彈出輸入法。 然后
onBackPressed
方法,但現在隱藏了輸入方法。 onBackPressed
方法。 我的問題是,為什么第一次不調用onBackPressed
方法? 我該如何運作呢?
這是我的代碼。
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();
}
}
<?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>
您可以為其添加一個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;
}
});
EditText擁有自己的偵聽器,並且在按下時可以在編輯窗口處於活動狀態時進行響應。 當活動本身直接監聽點擊時,onBackPressed()方法有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.