我创建了一个水平的LinearLayout,其中包含一个EditText和一个按钮。按钮应该尽可能窄,而EditText应该占据整个剩余空间。
我写了这段代码
<LinearLayout
android:id="@+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/editTextToSpeak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:hint="@string/text_to_speak"
android:inputType="text" />
<Button
android:id="@+id/saveCard"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/save_card" />
</LinearLayout>
然后我得到了这样的画面:
按钮完全不可见,而EditText的高度增加了一倍。
如何让这些元素看起来像第一张图一样?
你可以通过使用 android:layout_weight="1"
和 android:layout_width = "0dp"
在你的EditText中,所以它将占据除了你的按钮区域以外的其余空间。
<LinearLayout
android:id = "@+id/textInputLayout"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "horizontal">
<EditText
android:layout_weight="1"
android:id="@+id/editTextToSpeak"
android:layout_width="0dp"
android:layout_height="match_parent"
android:ems="10"
android:hint="@string/text_to_speak"
android:inputType="text" />
<Button
android:id="@+id/saveCard"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/save_card" />
</LinearLayout>
希望能帮到你:)
使用android:weightSum & android:weight。它将使你能够固定垂直或水平的大小。
<LinearLayout
android: id = "@ + id / textInputLayout"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: orientation = "horizontal"
android:weightSum="3">
<EditText
android: id = "@ + id / editTextToSpeak"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: ems = "10"
android: hint = "@ string / text_to_speak"
android: inputType = "text"
/>
<Button
android: id = "@ + id / saveCard"
android: layout_width = "wrap_content"
android: layout_height = "match_parent"
android: text = "@ string / save_card"
android:layout_weight="1"/>
你也可以使用android中的相对布局来实现。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<EditText
android:id="@+id/editTextToSpeak"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/text_to_speak"
android:inputType="text"
android:layout_toStartOf="@+id/saveCard"/>
<Button
android:id="@+id/saveCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save_card"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
希望对你有所帮助。)