Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TextView baseline related margin

Tags:

android

layout

I need to position a TextView the way its baseline is 20dp from the bottom of the container.

How can I achieve this?

The layout with bottom margin or padding produces the same result.

I would like to make the text 'sit' on the purple line. When I write 'sit' I mean, the 'wert' should touch the line, not 'q...y'.

The padding / margin is equal to the purple square size:

enter image description here

like image 318
aguyngueran Avatar asked Jan 11 '15 10:01

aguyngueran


2 Answers

If you still need it, I wrote custom method, to not create lots of custom views. It works for me with TextView:

public static void applyExistingBotMarginFromBaseline(View view) {
    final int baseline = view.getBaseline();
    final int height = view.getHeight();

    final ViewGroup.MarginLayoutParams marginLayoutParams;
    try {
      marginLayoutParams = ((ViewGroup.MarginLayoutParams) view.getLayoutParams());
    } catch (ClassCastException e) {
      throw new IllegalArgumentException("Applying margins on a view with wrong layout params.");
    }

    final int baselineMarginValue = baseline + marginLayoutParams.bottomMargin;

    marginLayoutParams.bottomMargin = baselineMarginValue - height;

    view.setLayoutParams(marginLayoutParams);
}

You can apply it when view is measured already, so like this:

final TextView title = (TextView) findViewById(R.id.title);

title.post(new Runnable() {
      @Override public void run() {
        Utils.applyExistingBotMarginFromBaseline(title);
      }
});

Also you can use databinding framework and write your own custom BindingAdapter with a bit customized method, to use it from xml.

like image 122
Anton Shkurenko Avatar answered Nov 15 '22 01:11

Anton Shkurenko


Your problem is not the padding/margin referenced to the parent, I think is about your font, I recommend you to change the fontFamily:"yourStyle" even worst you have to re-difine your own font style which is explained here Custom fonts and XML layouts (Android) or Set specific font in a styles.xml

like image 30
Carlos Zerga Avatar answered Nov 15 '22 01:11

Carlos Zerga