简体   繁体   中英

Get available width for TextView with layout_width=“wrap_content”

I have a complex layout that has TextView with layout_width="wrap_content" . I want to get maximum width that this TextView can fill.

Is there a universal way to do it? Or should I go over all parents and calculate their margins, paddings, etc? How does Android do it?

You can get it's parent and calculate it's width like this. This width would be the maximum width the TextView can take provided the parent has no padding.

View parent = (View) textView.getParent();
int width = parent.getWidth();

If the parent has some padding you'll need to compute it separately and subtract from this width.

int paddingE = parent.getPaddingEnd();
int paddingS = parent.getPaddingStart();
int totalWidth = width - (paddingE + paddingS);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM