如何限制editText的宽度

时间:2015-01-17 09:46:13

标签: android android-layout android-edittext

在下面发布的布局中,editText总是拉伸到最后,即使我将其宽度限制为像30dp我希望它不会延伸到最后,怎么能我这样做了

* XML代码

    <?xml version="1.0" encoding="utf-8"?>
<TableLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TableRow 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top|left"
    android:orientation="horizontal">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|center_vertical"
        android:src="@android:drawable/alert_light_frame"/>
    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|center_vertical"
        android:text="roll: "/>
    <EditText 
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:hint="E"
        android:ems="6"/>
</TableRow>

3 个答案:

答案 0 :(得分:0)

使用android:maxWidth属性:

<EditText
    android:layout_width="30dp"
    android:layout_height="wrap_content"
    android:gravity="start"
    android:hint="E"
    android:ems="6"
    android:maxWidth="30dp"/>

答案 1 :(得分:0)

始终使用wrap_content而不是Edittext,Textview等中的任何值,并尝试使用&#34; sp&#34;而不是dp。请尝试以下代码:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="start"
    android:hint="E"
    android:ems="6" />

永远不要在XML中定义表格布局中的表格行,更可取的方法是动态创建行,如下所示,请尝试以下代码。

TableLayout tl;
tl = (TableLayout) findViewById(R.id.mainTable)
tr = new TableRow(this);

label = new TextView(this);
label.setText("GFD");
label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
label.setPadding(5, 5, 5, 5);
label.setBackgroundColor(Color.parseColor("#FF1493"));
LinearLayout Ll = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(5, 5, 5, 5);
Ll.addView(label,params);
tr.addView((View)Ll);

tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

答案 2 :(得分:0)

尝试将wrap_content用于TableLayoutTableRow的宽度:

<TableLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

    <TableRow 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top|left"
    android:orientation="horizontal">
相关问题