2012-09-28 37 views
1

我有TableLayout如下:我如何設置單元格高度爲android tablelaayout中的寬度?

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:stretchColumns="1"> 

<TableRow> 
    <Button 
    android:id="@+id/b1" 
    android:layout_width="0dip" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" 
    android:gravity="center" /> 
    <Button 
    android:id="@+id/b2" 
    android:layout_width="0dip" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" 
    android:gravity="center" /> 
    <Button 
    android:id="@+id/b3" 
    android:layout_width="0dip" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" 
    android:gravity="center" /> 
</TableRow> 
</TableLayout> 

每個按鈕具有相同的寬度。 我希望這些按鈕的高度與它們的寬度完全相同。 我試圖做到這一點programmally:

Button b1 = (Button) findViewById(R.id.b1); 
b1.setHeight(b1.getWidth()); 

,但它不工作(它給我的0值)。我想這是因爲當我這樣做的時候(在onCreate方法中)按鈕還沒有設置。

+0

這是一個可以給你解決了類似的問題:http://stackoverflow.com/questions/2948212/android-layout-with-sqare-buttons –

回答

1

首先,你是對的,你得到的值爲0,因爲當你試圖獲得按鈕width時,屏幕還沒有繪製。

正如我所看到的那樣,唯一可行的方法就是在XML文件中爲他們提供預定義值。

例如:

<Button 
    android:id="@+id/b1" 
    android:layout_width="25dip" 
    android:layout_height="25dip" 
    android:gravity="center" /> 

設置寬度和高度programmally:

DisplayMetrics metrics = new DisplayMetrics(); 
getWindowManager().getDefaultDisplay().getMetrics(metrics); 

btnWidth = metrics.heightPixels/3 - 50;//gap 
btnHeight = btnWidth; 

Button b1 = (Button) findViewById(R.id.b1); 
b1.setHeight(btnWidth); 
b1.setWidth(btnWidth); 
+0

問題是,我想要3個方格,這將是所有的屏幕寬度 – LiorZ

+0

@LiorZ你是對的,如果你使用這種方法,你不能使用'android:layout_weight '。那麼你是不是從一開始就給所有的按鈕等寬?你可以在xml文件中完成它,或者當你創建屏幕時,獲得你的設備寬度,用3分開,並在它們之間加一點空白,然後編程設置它。 –

+0

我不知道從一開始的寬度,因爲我想要的按鈕是在相同的寬度,將遍佈屏幕的寬度,我只能用xml來做到這一點。 我試圖通過將屏幕劃分爲3來編程,並使用此值佈局按鈕,但方法佈局使用整數,並且按鈕的寬度可能是雙倍,因此會產生醜陋的空白。但是,當我使用XML它解決了這個問題。 – LiorZ

相關問題