(转载)http://blog.csdn.net/liao277218962/article/details/46876117
问题在于以下函数:
public void setBackgroundResource (int resid) Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.也就是说,其实 setBackgroundResource接着调用的应该是:setBackgroundDrawable函数,让我们看看setBackgroundDrawable的描述:
public void setBackgroundDrawable (Drawable d) Since: API Level 1 Set the background to a given Drawable, or remove the background.If the background has padding, this View's padding is set to the background's padding. However, when a background is removed, this View's padding isn't touched. If setting the padding is desired, please use setPadding(int, int, int, int).Parametersd The Drawable to use as the background, or null to remove the background
也就是说,因为9-patch有自己的padding,所以convertView自己的padding被覆盖了!那可咋办呢?其实知道这个了就很简单了,只要在代码setBackgroundResource之后加上(Remember:一定是这句之后!)一句:
view.setPadding(0, 0, 0, 0);
就可以解决问题了~
//------------------------------------------------------------------------------------------------------------
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="48px"
android:background="@drawable/icon_nav_message"
android:gravity="center"
android:minWidth="48px"
android:textSize="36px"
android:textColor="@color/white"/>
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText("19");
tv.setBackgroundResource(R.drawable.icon_nav_message);
tv.setPadding(10, 0, 10, 0);