【问题标题】:Get height and padding size获取高度和填充大小
【发布时间】:2015-04-24 13:39:40
【问题描述】:

我想查看 textview 的高度和 textview 的填充的总和。 我用方法设置填充:

textView.setPadding(0,x,0,x);

但是如果我使用

textView.getHeight();

我会收到 0。

如果我使用

ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) textView.getLayoutParams();
Log.d(TAG,params.height+"");

我会收到 -2 这是不可能的。

我该怎么办?

编辑:这是 XML 代码

<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/try"
            android:textColor="#fff"
            android:id="@+id/tv"
            android:gravity="center_horizontal" />

Edit2:我使用此代码设置文本视图的宽度,它工作正常。

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
final int width = size.x;
final int height = size.y;
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) textView.getLayoutParams();
params.width = width/2;

我不想以编程方式设置高度,因为我设置了填充。但我想得到衡量标准

编辑3:

我尝试使用

Rect bounds = new Rect();
textView.getPaint().getTextBounds(textView.getText(), 0,textView.getText().length(), bounds); 
bounds.height(); //This should give you the height of the wrapped_content

正如 Slartibartfast 告诉我的那样。但是有一个问题:

这可能是文本大小的测量值......但这不是文本视图高度的正确测量值。我试图将这个数字和 2 的填充度量相加并尝试设置:

params.height = bounds.height() + 2*x;

视图比没有这行代码的视图小。

【问题讨论】:

  • -2 通常意味着您使用 MATCH_PARENT 或 WRAP_CONTENT(这些是分配的常量)作为高度属性。你也可以粘贴textview的xml吗?
  • 编辑完成!这是我的代码!是否可以在 wrap_content 视图中计算实际高度?

标签: android android-layout textview


【解决方案1】:

看看:How to retrieve the dimensions of a view?

基本上只有布局完成后才知道大小,一种方法是创建自定义文本视图并使用onSizeChanged方法

编辑:

怎么样

Rect bounds = new Rect();
textView.getPaint().getTextBounds(textView.getText(), 0,textView.getText().length(), bounds); 
bounds.height(); //This should give you the height of the wrapped_content

【讨论】:

  • 我读到 getHeight() 已被弃用,我必须使用 getSize(Point x)。但我不明白如何在这种情况下使用它。我用它来设置 TextView 的宽度,现在我将编辑
猜你喜欢
  • 2013-02-19
  • 2017-02-02
  • 2021-05-19
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多