【问题标题】:Android default focus behavior in new API versions新 API 版本中的 Android 默认焦点行为
【发布时间】:2021-01-09 02:28:44
【问题描述】:

我有一个带有单个 EditText 的简单测试应用程序。当我在 API 24 设备上运行它时,此 EditText 在应用程序启动后默认聚焦。但是当我在较新的 Android API 版本(例如 API 28)上运行它时,应用程序启动后我没有焦点视图。 这是Java代码:

public class MainActivity extends AppCompatActivity {

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

这是布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edtMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:hint="hint"/>
</androidx.constraintlayout.widget.ConstraintLayout>

这是我的 build.gradle 的一部分:

compileSdkVersion 30
buildToolsVersion "30.0.2"

defaultConfig {
    applicationId "com.gmail.kapusta.yu.focustest"
    minSdkVersion 16
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

而且,当我将 targetSdkVersion 设置为 26 时,我会收到“旧”行为,其中 EditText 默认集中在 API 28 设备上。

所以,问题是:

  1. 为什么我们在不同的版本中会有这样的行为?
  2. 当 targetSdkVersion 为 30 甚至更多(将来)时,如何在新设备上获得默认关注 EditText 的“旧”行为?

我知道我可以在 onResume() 中调用 requestFocus(),例如,但这似乎不是一个好方法。

【问题讨论】:

    标签: java android layout focus


    【解决方案1】:

    官方文档确认,自 targetSdkVersion 28 https://developer.android.com/about/versions/pie/android-9.0-changes-28#focus 以来,视图并未隐式聚焦。因此,我们必须按照此处https://stackoverflow.com/a/51950681/95313 的描述明确地执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 2020-05-25
      相关资源
      最近更新 更多