2013-10-14 42 views
39

我在GridLayout的底部创建了一个TextView,其中带有一个可绘图。Android TextView可绘制,更改可绘制和文本之间的填充?

我想把drawable带到TextView的中间;我尝试了 setCompoundDrawablePadding(-75),它只改变文本的位置。

当前代码:

TextView secondItem = new TextView(this); 
    GridLayout.LayoutParams second = new GridLayout.LayoutParams(row2, col1); 
    second.width = halfOfScreenWidth; 
    second.height = (int) (quarterScreenWidth * 1.5); 
    secondItem.setLayoutParams(second); 
    secondItem.setBackgroundResource(R.color.MenuSecond); 
    secondItem.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, R.drawable.ic_action_new); 
    secondItem.setText("Text"); 
    secondItem.setCompoundDrawablePadding(-180); 
    secondItem.setGravity(Gravity.CENTER); 
    secondItem.setTextAppearance(this, android.R.style.TextAppearance_Large_Inverse); 
    gridLayout.addView(secondItem, second); 

如何设置文本并绘制​​到TextView的中间?

回答

86

您需要结合drawablePaddingpadding才能得到想要的结果。

+0

谢谢!它有助于。 – user1648374

+0

你会如何将它合并为不同的文本(例如不同的区域设置)? – orium

0

您可以使用图层列表。

前:

enter image description here

的形状创建XML - shape_rectangle.xml:

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:right="5dp"> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
     <solid android:color="@color/my_color" /> 
     <size 
      android:width="5dp" 
      android:height="5dp" /> 
    </shape> 
</item> 
</layer-list> 

后:

enter image description here

在XML中,有像android:right。您也可以添加topleftbottom。通过这种方式,您可以举例说明:无需调整textView的总高度即可左右绘制drawable。

4

在XML:

机器人:drawablePadding = paddingValue

编程:

TextView的TXT;

txt.setCompoundDrawablePadding(paddingValue)

安卓drawablePadding是给填充到绘制图标的最简单的方法,但你不能给出具体的一面填充像paddingRight或绘制图标的paddingLeft。这可以在可绘制的任一侧填充填充。

0
<Button 
      android:id="@+id/otherapps" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:background="@drawable/btn_background" 
      android:text="@string/other_apps" 
      android:layout_weight="1" 
      android:fontFamily="cursive" 
      android:layout_marginBottom="10dp" 
      android:drawableLeft="@drawable/ic_more" 
      android:paddingLeft="8dp" //for drawable padding to the left 
      android:textColor="@android:color/holo_red_light" />`enter code here`