android 根据设备的大小增加字体大小

7kjnsjlb  于 12个月前  发布在  Android
关注(0)|答案(8)|浏览(121)

我计划使用不同的字体大小的textview在不同的设备大小,使字母易读。我已经决定不为不同的设备使用不同的布局,并建立了一个通用的布局,以适应所有的设备。现在唯一的问题是文字的大小。
问题:
1.我想有你的技术建议,如何改变字体大小的基础上的大小(物理大小)的设备。
1.如何根据纵横比导出字体大小。
1.使用这种方法有什么缺点吗?
文本视图的XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvValue4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="I planned to use different font size for the textview on different device size so as to make the letters legible. I have already decided not to use different layouts for different devices and built a common layout to fit in all the devices. Now the only problem is on the text size."
        android:textColor="#000000"
        android:textSize="15sp" />

</LinearLayout>

Thanks in advance

yfjy0ee7

yfjy0ee71#

是的,这种方法是有缺陷的。Android设备有不同的尺寸,但它们也可以有非常不同的密度。

你应该只遵循Android设计best practices

它们其实是经过深思熟虑的。你为什么要重新发明轮子呢?

lskq00tm

lskq00tm2#

试试这个,在你的xml中添加这个属性。它会根据屏幕大小调整文本大小,试试吧。

style="@android:style/TextAppearance.DeviceDefault.Medium"
2w3kk1z5

2w3kk1z53#

对于字体大小,使用缩放像素(sp)。Android将根据设备密度相应地缩放字体大小。上面的帖子有更好的解释和推理。

yi0zb3m4

yi0zb3m44#

String s= "hello";
    TextView tv= (TextView) findViewById(R.id.tv);
    Spannable span = new SpannableString(s);
    span.setSpan(new RelativeSizeSpan(5f), 0, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    tv.setText(span);

根据屏幕大小改变5f到任何你想要的。
http://developer.android.com/guide/practices/screens_support.html。查看标题最佳实践下的主题。

pdsfdshx

pdsfdshx5#

对于API 26及更高

<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:autoSizeTextType="uniform" />

来源:https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview

oxf4rvwz

oxf4rvwz6#

Android已经内置了这方面的工具- dp和sp。dp是设备像素。它基本上是1dp=1/160英寸。这允许您指定字体的高度在真实的世界大小。Sp是缩放的像素。此大小基于默认字体大小进行缩放,因此用户可以放大其系统字体,您的应用将与之匹配。方便的人与视力问题谁需要大文本,而不占用屏幕真实的房地产为他人。
你应该用其中一个。

ijnw1ujt

ijnw1ujt7#

对于这个问题,我在很多项目中使用了以下库,相信这是非常棒的。不用担心屏幕。但同样,您需要为选项卡创建单独的布局。
https://github.com/intuit/sdp

pgvzfuti

pgvzfuti8#

字体大小根据屏幕大小

public static void applyFont(TextView tv, Float fontSize) {
    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize * fontFactor);
}

public static float fetchFontFactor(Activity act) {

    DisplayMetrics displayMetrics = new DisplayMetrics();

    act.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

    float returnFactor = ((float) displayMetrics.widthPixels ) / 1280.0f;

    return returnFactor;
}

在MainActiviy.java我有

fontFactor = fetchFontFactor(this);

现在的问题是,我的代码中的1280是什么。
答案是,这只是设计师提供的设计宽度。如果设计师给出的设计尺寸为1080x1920,您可以将1280替换为1080。
因此,如果设计师在设计中使用55字体,我们可以使用55如下。

applyFont(titleTV, 55f);

这适用于两个方向.

相关问题