如何计算字符串字体宽度,以像素为单位

Bal*_*ake 11 java android

我想在android中计算字符串字体宽度(以像素为单位).我有字符串数组,我将所有这些数组元素附加到一个字符串.所以我必须在两个连续的数组元素之间设置固定的间距.我将这个最后的字符串放入textview.最后,我将此textview添加到tablerow.总之,我想查看具有标题和值的表结构.我在这里看过很多帖子,但没有得到解决方案.

提前致谢...!!!

Jak*_*ile 21

看起来有measureText一种可用的方法Paint.我也找到了一个例子:

mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(5);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setTextSize(64);
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
// ...
float w = mPaint.measureText(text, 0, text.length());
Run Code Online (Sandbox Code Playgroud)


Voy*_*Voy 5

感谢杰克的工作解决方案,但我发现这对我也有用:

someText = "Lorem Ipsum";
TextView myTextView = (TextView) findViewById(R.id.myTextView);
float w = myTextView.getPaint().measureText(someText);
Run Code Online (Sandbox Code Playgroud)

直接从我将要使用的 TextView 获取 Paint 让我觉得 anwser 会更准确。