2015-01-14 67 views
0

我有一個textview組件,我通過layout_weight將其寬度設置爲其父窗口的50%。我也需要爲它設置一個填充值。看來我可以將它設置爲xdp,但我如何使用weight config?比如說,左填充爲屏幕的2%?android:paddingLeft設置爲屏幕的百分比

<TextView 
     android:id="@+id/buttonCollect" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:text="@string/hello" 
     android:paddingLeft="8dp" //<---- how to se this. 
     android:layout_weight="0.5" /> 

回答

1

您不能將百分比設置爲XML佈局文件中的填充值。

但是,您可以通過計算px中的正確長度來將其設置爲Java代碼。

+0

謝謝。如果我想將寬度設置爲父級的90%,而高度爲父級的80%,則將其設置爲0dp。我應該如何設置layout_weight?因爲它似乎有一個layout_weight – Hammer

0

您可以使用dimens.xml並將它們放在不同的values-xxx文件夾中。如果妳想要在hdpi設備8dp10dphdpi-1024x600,U可以按照下列步驟操作:

  1. values-hdpi文件夾中創建dimens.xml

    <?xml version="1.0" encoding="utf-8"?> 
    <resources> 
        <dimen name="paddingLeft">8dp</dimen> 
    </resources 
    
  2. values-hdpi-1024x600文件夾中創建dimens.xml

    <?xml version="1.0" encoding="utf-8"?> 
    <resources> 
        <dimen name="paddingLeft">10dp</dimen> 
    </resources 
    
  3. 更換android:paddingLeft="8dp"android:paddingLeft="@dimen/paddingLeft"

希望它能幫助。

0

您可以使用水平的LinearLayout查看的TextView作爲其子,並相應分配權重。然後,不需要將填充設置爲TextView

這裏,TextView需要2/3的屏幕。

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:orientation="horizontal" > 

     <RelativeLayout 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="2" /> 

     <TextView 
      android:id="@+id/textView1" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="Lagre text" 
      android:textAppearance="?android:attr/textAppearanceLarge" /> 

    </LinearLayout> 
相關問題