2011-05-11 58 views
0

我将EditText元素的宽度设置为fill_parent在XML文件中,但是当从代码访问它时,它返回0. 我想要的是该元素在运行时的实际宽度。我怎么能这样做。设置EditText的宽度

回答

2

使用getMeasuredWidth():http://developer.android.com/reference/android/view/View.html#getMeasuredWidth%28%29

读也在这里:

当一个视图的measure()方法返回,必须设置其getMeasuredWidth()和getMeasuredHeight()值,以及所有该View的后代的值。视图的测量宽度和高度测量值必须符合视图父母强加的约束条件。这保证了在测量结束时,所有父母都接受他们所有孩子的测量。父视图可能会多次调用measure()对其子进行调用。例如,父母可以用未指定的维度来测量每个孩子一次,以找出他们想要的大小,然后如果所有孩子的无约束尺寸的总和过大或过小,则再次用实际数字对它们调用measure()(即如果孩子之间不同意他们各自获得多少空间,那么父母将介入并在第二遍设置规则)。

http://developer.android.com/guide/topics/ui/how-android-draws.html

+0

'getMeasuredWidth()'也返回零。 – Greenhorn 2011-05-11 05:17:54

+0

@Greenhorn是绘制的视图?除非它已被绘制到窗口上,否则不会设置其宽度。 – Aleadam 2011-05-11 05:20:08

+0

是的,我从'onConfigurationChanged()'和'onStart()'调用它。 – Greenhorn 2011-05-11 05:25:42

1

您可以通过创建自定义视图并重写onMeasure()方法来解决此问题。如果您在xml中始终使用“fill_parent”作为layout_width,那么传递给onMeasusre()方法的widthMeasureSpec参数应该包含父级的宽度。

public class MyCustomView extends EditText { 

public MyCustomView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec); 
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec); 
} 
} 

你的XML会是这个样子:

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <view 
     class="com.company.MyCustomView" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 
</LinearLayout> 
0

我将把你前面的回答关于这一主题,应该是有帮助的:

How to retrieve the dimensions of a view?

+0

使用这种方法,我得到了宽度,但将其设置为其他EditText元素的宽度,但它们没有反映它。我想要做的是使所有的EditTexts具有相同的宽度。 – Greenhorn 2011-05-11 05:52:11

+0

您可能想使用TableLayout进行研究。你用什么代码来设置其他的宽度? – kcoppock 2011-05-11 11:58:12