如何将edit texts放置在fragment中并固定login/signup按钮位置
实现方案
核心逻辑:不要将Login/Signup按钮放入Fragment布局内,需将按钮放在承载Fragment的宿主Activity的根布局中,与Fragment容器同级且固定在底部,切换Fragment时按钮位置不会发生任何变化
具体实现步骤(ConstraintLayout方案,推荐)
- 编写宿主Activity的布局文件,结构如下:
<?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" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- Fragment容器,承载登录/注册的Fragment(内含EditText) --> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@id/btn_group" /> <!-- 底部固定的按钮组 --> <LinearLayout android:id="@+id/btn_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp" app:layout_constraintBottom_toBottomOf="parent"> <Button android:id="@+id/btn_login" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Login" android:layout_marginEnd="8dp"/> <Button android:id="@+id/btn_signup" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Sign Up" android:layout_marginStart="8dp"/> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
- 配置软键盘适配规则,在
AndroidManifest.xml对应的Activity标签下添加以下属性,避免软键盘弹出时按钮错位、输入框被遮挡:
<activity android:name=".YourAuthActivity" android:windowSoftInputMode="adjustResize" />
- 原有Fragment的逻辑无需修改,只需要确保Fragment布局的根布局高度为
match_parent即可,Fragment的内容会自动展示在按钮上方的区域,不会和按钮重叠。
参考效果示意图


可选LinearLayout实现方案
如果偏好使用LinearLayout作为根布局,可使用权重实现固定效果:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <!-- 按钮组代码和上述方案一致 --> <LinearLayout android:id="@+id/btn_group" android:layout_width="match_parent" android:layout_height="wrap_content" ...> ... </LinearLayout> </LinearLayout>
内容的提问来源于stack exchange,提问作者Hager Khaled
相关产品推荐
相关产品推荐

