2

我想實現以下目標:如何創建一個Button至少和TextView一樣長的佈局?

  • 我需要的地方放置一個Button視圖佈局
  • 應該有TextView權這Button就是上面使用的標籤
  • 的大小Button應取決於TextView的大小。由於該應用是本地化的,因此文本寬度並不固定,而是取決於用作標籤的本地化文本。
  • Button應該有一個分鐘。寬度爲150dp。如果TextView的寬度大於此值,則Button應與TextView具有相同的寬度。

這應該是這個樣子:

Short Label 
+-------------+ 
+-------------+ 

Very Long Label Text 
+------------------+ 
+------------------+ 

我試着用的LinearLayout或RelativeLayout的不同解決方案根佈局,但問題始終是相同的:我是不是能夠適應Button的寬度到TextView的寬度。給予Button 150dp的最小寬度當然不成問題。但如何解決長標籤的第二種情況?

<SomeRootLayout ...> 
    <!-- also tried LinearLayout, but problem is the same... --> 
    <RelativeLayout 
     android:id="@+id/editTextAndLabelContainer" 
     ...> 

     <TextView 
      android:id="@+id/labelTV" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="A " /> 

     <Button 
      android:id="@+id/button" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/labelTV" /> 
    </RelativeLayout> 
</SomeRootLayout> 

如果Button有一個「match_parent」寬寬度不對齊的TextView但設置爲完整的屏幕寬度。

我該如何解決這個問題?

+0

通過getwidth()爲文本視圖執行編程...如果大於則按鈕的寬度與textview相同。 – Ranjit

回答

4
<RelativeLayout 
     android:id="@+id/editTextAndLabelContainer" 
     ...> 

     <TextView 
      android:id="@+id/labelTV" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="A " /> 

     <Button 
      android:id="@+id/button" 
      android:layout_alignLeft="@+id/labelTV" //<== add this line 
      android:layout_alignRight="@+id/labelTV" //<== add this line 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/labelTV" /> 
    </RelativeLayout> 
+0

非常感謝!我不知道可以合併不同的路線......這個解決方案完美地工作! –

1

Ok..do類似: 佈局:

<LinearLayout 
    android:id="@+id/editTextAndLabelContainer" 
    android:weightSum="2" 
    ...> 

    <TextView 
     android:id="@+id/labelTV" 
     android:layoutWeight="1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="A " /> 

    <Button 
     android:id="@+id/button" 
     android:layoutWeight="1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/labelTV" /> 
</LinearLayout> 

或者由莉娜作爲建議..

而且在Java代碼: 在你的TextView ontextchange方法添加TextWatcher ..並且在textchange方法之後執行如下操作:

int txtWidth = your_textViw.getWidth(); 
int btnWidth = your_button.getWidth(); 

if(txtWidth >= btnWidth) 
    your_button.setWidth(txtWidth); 
相關問題