2016-08-29 60 views
0

我有一個簡單GridLayout的Android GridLayout的fill_horizo​​ntal熄滅屏幕

<GridLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:columnCount="2" 
    android:rowCount="1" > 

    <TextView 
     android:layout_column="0" 
     android:layout_row="0" 
     android:text="Label"/> 

    <EditText 
     android:inputType="text" 
     android:layout_column="1" 
     android:layout_row="0" 
     android:text="asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf" 
     android:layout_gravity="fill_horizontal"/> 
</GridLayout> 

然而,這將導致EditText延長關閉屏幕,如下面(圖像從所述IDE中可以看出,但它同樣的時在設備上運行)。

enter image description here

看來,EditText實際上是在屏幕的整個寬度,而不是GridLayout細胞,這就是爲什麼它會關閉屏幕的寬度。造成這種情況的佈局出了什麼問題?

+1

http://stackoverflow.com/questions/30845440/edittext-getting-out-of-gridlayout看到這個 – KrishnaJ

回答

0

我不確定爲什麼你需要GridView的情況下,也許你知道我更好,但你可以在這篇文章Gridview with two columns and auto resized images找到對你有用的東西。

在你的情況下,GridView有2列,每一個裏面你有沒有設置任何值的寬度和高度參數的視圖,在這種情況下Android是除了他們的wrap_content。

當TextView和EditText具有layout_width =「wrap_content」時,它們會將它們自行擴展到一行,直到它們包裹整個內容爲止。這就是爲什麼你要走出手機屏幕。

試試這個XML,你會看到預期的行爲:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:columnCount="2" 
android:rowCount="1"> 
<TextView 
    android:layout_width="20dp" 
    android:layout_height="wrap_content" 
    android:layout_columnWeight="0.5" 
    android:layout_column="0" 
    android:text="Label with some long text event more text"/> 
<EditText 
    android:layout_width="50dp" 
    android:layout_height="wrap_content" 
    android:layout_columnWeight="1.5" 
    android:inputType="textMultiLine" 
    android:layout_column="1" 
    android:text="Some really long text here and more and more and more .... " 
    android:layout_gravity="fill_horizontal"/> 

我們在這裏做的僅僅是設置爲你的孩子一些硬編碼值(的TextView和EditText上),對他們的Android :layout_width屬性,並給它們android:layout_columnWeight屬性。這將設置你的列的一些比例(玩這個值只是爲了滿足你的需要)。

使用EditText,我們也在做一些小事(android:inputType =「textMultiLine」),以確保您的文本將被包裝在多行上。

順便說一句:如果你正在做一些輸入表單,我會建議你使用LinearLayout這樣的其他ViewGroups。

謝謝任何​​問題請發表評論。

+0

謝謝你的迴應。這個例子被削減以專注於這個問題,這就是爲什麼它是簡單化的。該問題的評論中指出瞭解決方案,即將layout_width設置爲0dp。 – jgm

+0

我不知道爲什麼你給我-1這個迴應,當你正在做同樣的東西來解決問題(設置0dp到你的寬度attr),但任何爲什麼我不能做任何事情。我的答案是接受否定的投票沒有錯 – Sniper

+0

我沒有選擇你的答案是正確的,因爲它使用固定的寬度,它不會提供所需的結果來填充屏幕的寬度,但不會掉到邊緣。 – jgm