简体   繁体   English

使用layout_width =“ wrap_content”获取TextView的可用宽度

[英]Get available width for TextView with layout_width=“wrap_content”

I have a complex layout that has TextView with layout_width="wrap_content" . 我有一个复杂的布局,该布局具有TextView和layout_width="wrap_content" I want to get maximum width that this TextView can fill. 我想获得此TextView可以填充的最大宽度。

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? Android如何做到这一点?

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. 如果父级没有填充,则此宽度将是TextView可以采用的最大宽度。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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