美文网首页Android深入
Android仿京东字体设置功能

Android仿京东字体设置功能

作者: 馒头炖土豆 | 来源:发表于2021-04-29 11:36 被阅读0次

需求:
京东APP在设置页面,有“字体设置”功能,点击进去后可以设置大字号和标准字号,经产品和开发协商,我们这边的需求定为:在APP中增加一个类似于京东的设置页面,点击设置后APP中指定页面的指定文案变成大字号,每个文案放大的比例不一定相同,产品会规定好每个文案的原始字号和放大后的字号。

实现:
自定义一个TextView,在xml中声明需要放大到的字号,通过一个本地数据库中存储的值来判断是否需要放大,如果需要,就在自定义的TextView中重新设置字号;根据产品的需求在需要放大文案的页面使用自定义TextView.

ZoomTextView全部代码

package com.example.myapplication;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

import androidx.annotation.Nullable;

public class ZoomTextView extends TextView {

    public ZoomTextView(Context context) {
        super(context);
    }

    public ZoomTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.ZoomTextView);
        float scal_to_textSize = ta.getDimensionPixelSize(R.styleable.ZoomTextView_scal_to_textSize, -1);//要缩放到的字号
        ta.recycle();

        if (scal_to_textSize > 0 && Word.isScal) //表示xml中设置了缩放比例
        {
            setTextSize(TypedValue.COMPLEX_UNIT_PX,scal_to_textSize);
        }
    }
}

attrs文件代码

<declare-styleable name="ZoomTextView">
        <attr name="scal_to_textSize" format="dimension"/>
    </declare-styleable>

xml代码

<com.example.myapplication.ZoomTextView
        android:layout_marginTop="30dp"
        android:id="@+id/tv_zoom"
        android:textSize="15dp"
        android:textColor="#000000"
        app:scal_to_textSize="18dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本" />

开关类代码

package com.example.myapplication;

public class Word {
    public static boolean isScal = true; //真正项目中可以用保存到本地数据库中的字段值代替,以实现永久化设置
}

相关文章

网友评论

    本文标题:Android仿京东字体设置功能

    本文链接:https://www.haomeiwen.com/subject/jkvirltx.html