这个是我以前发在EOE上的一个帖子,发现阅读量平平还是发到这里来装饰下我的博客吧。
废话不多说,首先先来说下TextView设置字体这个事情。系统默认的设置字体的方法是sp。先看下全称:sp: scaled pixels.scale顾名思义放缩比例,也就是说系统的sp其实是乘以一个固定的放缩比例设置的,那么我们是不是也做同样的设置呢。
有一个东西我们肯定要清楚,无论我们设置sp,dp其实到最后绘制的时候都是转化成px来使用的。所以我们可以回到一个原点,就是我们通过自己的效果图的大小去自己生成这么一个scale,去执行这个换算步骤。
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
TypedArray type = context.obtainStyledAttributes(attrs,
R.styleable.MyTextView);
int i = type.getInteger(R.styleable.MyTextView_textSizePx, 25);
setTextSize(TypedValue.COMPLEX_UNIT_PX, getFontSize(i));
}
// 获取当前手机屏幕分辨率 之后根据设计图分辨率高度去换算实际字体大小
private int getFontSize(int textSize) {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
int screenHeight = dm.heightPixels;
// screenWidth = screenWidth > screenHeight ? screenWidth :
// screenHeight;
int rate = (int) (textSize * (float) screenHeight / 1280);
return rate;
}
}
好了,同学们,从上面这段代码我们可以通过获取屏幕分辨率的方式去自己换算出我们的scale,之后我们只要去从我们的效果图中把这个字的高度是多少测量出来设置在这个自定义textview中就可以去实现textview的适配问题了。
下面我会把一些res文件里面的关键部分补全给大家看。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextView">
<!-- 自定义属性,format属性表示该属性的单位 -->
<attr name="textSizePx" format="integer" />
</declare-styleable>
</resources>
<com.example.mytextviewdemo.MyTextView
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
app:textSizePx="30" />