I needed to get constant aspect ratio of TextView with background image (9patch). So i used the code below in my activity:
@Override
public void onResume() {
super.onResume();
// adding contact image resize callback for adjusting image height
findViewById(R.id.contactText).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// aspect ratio
float resizeRatio = 1.13f;
// getting contact frame
TextView contactView = (TextView) findViewById(R.id.contactText);
ViewGroup.LayoutParams layout = contactView.getLayoutParams();
// resizing contact text
layout.height = (int) (contactView.getWidth() * resizeRatio);
contactView.setLayoutParams(layout);
contactView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
}
This code does what i expect - TextView is resized. But the borders (padding) for text, described in nine-patch are get from not resized image. So text is displayed in the center of TextView instead of bottom, where the padding borders are located.
How to fix this problem?
The problem is because of constant top padding of image even after stretch. When android stretches image vertically it keeps top padding value. So if padded area is not in stretched area it increases though it is not stretched at all.
This problem is described here