3

I have a TextView like so:

<TextView
   android:id="@+id/friends"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:padding="8dp" />

And I'm setting the background like:

textView.setBackgroundResource(R.drawable.background_color);

where background_color.xml is:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
        <solid android:color="#217dd2" />
    </shape>
</item>
<item
    android:left="5dip">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
        <solid android:color="#deebf6" />
    </shape>
</item>

This removes my default padding of 8dp and replaces it with the left padding of 5dp that I have declared on the 2nd item of the layered-list. Any way to avoid this? Or another way to create a 2 color background for a View?

ono
  • 2,984
  • 9
  • 43
  • 85

1 Answers1

2

That's known issue, setBackgroundResource method resets paddings. Try to set your background from XML:

<TextView
   android:id="@+id/friends"
   android:background="@drawable/background_color"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:padding="8dp" />

It will work properly in this case.

Community
  • 1
  • 1
Andrei Mankevich
  • 2,253
  • 16
  • 15
  • Ok, but I'm using this background as a selected state if you click on the view. The default would be just a solid white color. So I don't want to set it directly in the xml. – ono Jun 03 '14 at 15:01
  • If you need different backgrounds for selected and default states you should define it in xml as [selector](http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList) drawable. – Andrei Mankevich Jun 03 '14 at 15:04
  • Actually, I just realized I can set the padding after I set the background resource with `textView.setPadding(8, 8, 8, 8);` – ono Jun 03 '14 at 15:06
  • 1
    Yes, it can be an option. But beware that `setPadding` expects paddings in pixels, so if you want it to be density-independent you need to convert it. – Andrei Mankevich Jun 03 '14 at 15:08