在开发人员之间比较我们的设计时,我们发现了一个奇怪的行为。经过一些分析,我们进行了这次观察。
当 Activity 开始时,在某些情况下会出现键盘,但有时不会出现。
事实上,如果没有 ScrollView
,软键盘默认不会出现在 EditText
上。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
</LinearLayout>
但是当我们添加一个 ScrollView
时,默认情况下会显示软键盘。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestActivity" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
</ScrollView>
</LinearLayout>
它仅取决于 ScrollView
的存在。我们可以通过 AndroidManifest
中的特定声明来解决这个问题,但这是默认行为。
我和我的开发伙伴想知道为什么会这样?
最佳答案
以下是我在深入研究 Android 代码并使用 EditText
构建一些测试布局后对这个问题的理解。
因为 ScrollView
被定义为
public class More ...ScrollView extends FrameLayout { ... }
我尝试使用 FrameLayout
作为 EditText
项的容器。因此,不会触发软键盘。
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text" >
<requestFocus />
</EditText>
</FrameLayout>
但是正如问题中所写,使用 ScrollView 会触发软件键盘(我简化了 xml 源)。
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text" >
<requestFocus />
</EditText>
</ScrollView>
所以允许触发软键盘的元素在ScrollView
源文件中。
编辑:在创建了我自己的类 MyFrameLayout
扩展 FrameLayout 并使用代码后,我发现它是默认 ScrollView 样式 (R.attr.scrollViewStyle
) 负责键盘是否显示...
Edit2:最后,属性 android:scrollbars
允许键盘在启动时自动触发(如果存在)...
关于android - 为什么在 Activity 开始时软键盘显示或不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18721626/