2011-05-11 99 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