我正在尝试通过为 TextView.setLineSpacing() 设置一个负“添加”来减少 TextView 中的行距。它运作良好,除了底线被截断。
主要布局
<TextView
android:id="@+id/text_view"
android:padding="dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".MainActivity" />
主要 Activity :(注意
package com.font_test;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/custom_fonts.ttf");
final TextView tv = (TextView) findViewById(R.id.text_view);
tv.setTypeface(typeface);
tv.setTextSize(60);
tv.setLineSpacing(-30f, 1f); // *** -30 to reduce line spacing
tv.setBackgroundColor(0x280000ff);
tv.setText("gggkiiikkk" + "\n" + "gikgikgik" + "\n" + "kigkigkig");
}
}
这会导致 View 底部被截断(请注意底部的“g”):
问题似乎与布局测量不正确有关。如果我将 TextView 设置为
android:layout_height="fill_parent"
它确实正确呈现:
知道如何解决吗?如果有帮助,我不介意有丑陋的解决方法。我还可以访问 FontForge,如果需要,我可以修改字体文件。
最佳答案
littleFluffyKittys 的回答很好,但如果行距是通过 xml 设置的,它在某些设备上不起作用
我通过将字体的原始高度与 textview 为一行计算的高度进行比较来计算所需的额外高度。 如果行高小于字体高度,差值增加一次。
这至少适用于可能更低的 API 10(只是没有测试过更低)
public class ReducedLineSpacingTextView extends TextView {
public ReducedLineSpacingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ReducedLineSpacingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ReducedLineSpacingTextView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int truncatedHeight = getPaint().getFontMetricsInt(null) - getLineHeight();
if (truncatedHeight > 0) {
setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight() + truncatedHeight);
}
}
}
关于android - 如何减少TextView的行间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11924280/