I have a simple test app with a single EditText
. When I run it on API 24 device, this EditText is focused by default after app starts. But when I run it on newer Android API versions (API 28, for example), I have no focused view after app starts.
Here is Java code:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
And here is layout:
<?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>
And here is a piece of my 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"
}
And, when I set targetSdkVersion to 26, I receive "old" behavior with EditText focused by default on API 28 device.
So, the questions are:
- Why do we have such a behavior in different versions?
- How can I get the "old" behavior with default focus on EditText on new devices when targetSdkVersion is 30 and maybe more (in future)?
I know that I can call requestFocus() in onResume(), for example, but it does not seem to be a good way.