经常碰到需要把一个控件放在手机底部的情况,以前都是在LinearLayout尝试使用gravity=”bottom” ,但是,没有效果,后来在网上查到了方法,如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:layout_marginTop="12dp"
android:textSize="15sp"
android:textColor="#323232"
android:text="@string/master_clear_final_desc" />
<!--这个是关键,就是占满次下屏幕的所有位置-->
<LinearLayout
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"> </LinearLayout>
<Button android:id="@+id/execute_master_clear"
style="@style/SecurityPreferenceButtonFunuiConfirm"
android:text="@string/master_clear_final_button_text" />
</LinearLayout>
至于android:layout_height=”0dp” android:layout_weight=”1″ 它的意思就是,尽可能的占据父容器空闲的位置,而且,它不会把其他控件覆盖或者挤出去。
我们看如下的代码
<LinearLayout
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:background="@drawable/search_bg_funui"
android:orientation="horizontal"
android:layout_gravity="center_vertical"
> <EditText
android:id="@+id/search_actionbar_query_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@null"
android:gravity="center_vertical"
android:hint="@string/search_hint"
android:imeOptions="actionSearch|flagNoExtractUi"
android:inputType="text|textNoSuggestions"
android:nextFocusDown="@+id/search_overlay_suggestion_list"
android:paddingLeft="@dimen/search_main_text_padding"
android:paddingRight="@dimen/search_main_text_padding"
android:singleLine="true"
android:textAlignment="viewStart"
android:textColor="@color/search_query_text"
android:textColorHint="@color/search_query_hint_text"
android:textCursorDrawable="@drawable/display_input_cursor"
android:textSize="16sp" /> <ImageView
android:id="@+id/search_actionbar_ending_button"
android:layout_width="@dimen/search_ending_button_width"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackgroundBorderless"
android:scaleType="center" />
</LinearLayout>
在上述代码中, EditText尽量占有LinearLayout的位置,这样就会把ImageView挤到最边缘位置。但是,它的原则是,永远给同事控件保留设定的属性要求
我们经常会实现这样的功能,就是在listview底部跟一个按钮。而且,这个按钮一定要一直显示在底部。这时候,我们就可以通过设定listview的属性为
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
就行了,哪怕这时候listview没有item,listview也会尽可能充满这个屏幕,如果listview的item超过整个屏幕,它也会自动添加滚动条,而不会把下方的按钮挤出或覆盖