我感到困惑和沮丧的是,我无法让我的EditText字段在布局中占用合理数量的空间,而没有明确告诉它有多少像素。
我确定我遗漏了一些显而易见的东西,但我的经验是EditText完全忽略了layout_weight,并且如果我给它一个layout_weight为“wrap_content”或者需要,则使用输入的文本动态增长/缩小如果我给它一个fill_parent的权重,则在其父布局中占据大部分空间。
那么...有一个EditText字段占据其父布局的某些部分的正确途径(在我的情况下是Linear,但我很灵活),因此它旁边可以有一个标签,看起来像:
Name: [ EDIT TEXT HERE ]
Phone:[ EDIT TEXT HERE ]
等
TIA
答案 0 :(得分:2)
你可以做几件不同的事情。如前所述,您应该使用dp而不是像素进行布局。使用dp可以根据屏幕的物理尺寸而不是分辨率来缩放视图。
这是一个指定编辑框显示在每个标签右侧并占据屏幕剩余部分的示例:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_label"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Name:" />
<TextView
android:id="@+id/phone_label"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_below="@id/name_label"
android:text="Phone:" />
<EditText
android:id="@+id/name_text"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_toRightOf="@id/name_label" />
<EditText
android:id="@+id/phone_text"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_toRightOf="@id/phone_label"
android:layout_below="@id/name_text" />
</RelativeLayout>
以下是使用权重的LinearLayout示例:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="Name:"
android:layout_weight="1"/>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="Phone:"
android:layout_weight="1"/>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"/>
</LinearLayout>
</LinearLayout>
请注意,LinearLayout有7个视图,而RelativeLayout用5个视图完成类似的操作。 LinearLayouts非常方便,但它们更复杂。随着布局变得越来越复杂,它们的表现会比RelativeLayouts更差,尤其是嵌套时。
答案 1 :(得分:1)
对于每一行,请使用水平LinearLayout
。
在其中,添加水平LinearLayout
以“包裹”TextView
。将LinearLayout
layout_weight
设为20(例如)。
使用另一个横向LinearLayout
来“包裹”EditText
并将EditText
设置为fill_parent
,但将其外部LinearLayout
设为layout_weight
80(或任何基于20 + 80 = 100%的值,如果你明白我的意思)。
编辑:此外,如果您需要多行,然后简化整体布局文件,您可以定义“单行”布局文件并将其用作自定义布局条目。
答案 2 :(得分:0)
//为您的edittext设置最小宽度和最大长度
android:minWidth="40"
android:maxLength="30"
android:layout_width="wrap_content"
这样它总是显示最小宽度,你的角色不会超过30个。
答案 3 :(得分:0)
您需要使用Layout
。 LinearLayout
不适合您的布局。看看TableLayout
,我认为这可能符合您的要求。看看the TableLayout tutorial。