Background drawables define view size
This method works for me.
- clear the TextView background
- (in postRunnable) save TextView width and height
- (in postRunnable) set new background to TextView
- (in postRunnable) set width and height to TextView
Example
public void setTextViewBg(final TextView textView, final Drawable newBgDrawable) {
textView.setBackground(null);
textView.post(new Runnable() {
@Override
public void run() {
int width = textView.getWidth();
int height = textView.getHeight();
textView.setBackgroundDrawable(newBgDrawable);
LinearLayout.LayoutParams layoutParams = (LayoutParams) textView.getLayoutParams();
layoutParams.width = width;
layoutParams.height = height;
}
});
}
Hope it helps~
I have not tried this myself, but you could try this idea/hack/workaround:
The minimum height/width of a View (TextView) is determined by its background drawable (amongst other things). It uses the background Drawable's getMinimumHeight() and getMinimumWidth() to determine the View's minimum height and width.
It looks like you want the View's minimum height and width to be 0 (excluding padding) and the View's width/height should be based only on the View's content (in your case, the TextView's text).
Try this in the onCreate of your Activity or the onCreateView of your Fragment, where you get a hold of the TextView you are trying to 'fix'. Let's call this TextView 'tv':
TextView tv;
...
...
tv = (TextView)...findViewById(...);
....
// Swap the 'standard' bitmap background with one that has no minimum width/height.
BitmapDrawable background = (BitmapDrawable)tv.getBackground(); // assuming you have bg_tile as background.
BitmapDrawable newBackground = new BitmapDrawable(background.getBitmap) {
@Override
public int getMinimumWidth() {
return 0;
}
@Override
public int getMinimumHeight() {
return 0;
}
};
newBackground.setTileModeXY(background.getTileModeX(), background.getTileModeY());
tv.setBackgroundDrawable(newBackground);
...
...