为了改进 Instagram 中的 TextView 渲染,Instagram 的工程师在 here 中提供了一个 hack ,他们使用自定义 View (TextLayoutView)来缓存text.Layout,但是在这篇文章中,他们没有给我们演示或告诉我们如何使用它,所以如果我想使用这个hack,我该怎么做?
最佳答案
这是我的简单实现:
TextLayoutView:
public class TextLayoutView extends View {
private Layout mLayout;
public TextLayoutView(Context context) {
this(context, null);
}
public TextLayoutView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TextLayoutView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
long t1=System.currentTimeMillis();
super.onDraw(canvas);
canvas.save();
if (mLayout != null) {
canvas.translate(getPaddingLeft(), getPaddingTop());
mLayout.draw(canvas);
}
canvas.restore();
long t2=System.currentTimeMillis();
Log.i("TEST", "onDraw::"+(t2-t1));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
long t1=System.currentTimeMillis();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mLayout != null) {
setMeasuredDimension(
getPaddingLeft() + getPaddingRight() + mLayout.getWidth(),
getPaddingTop() + getPaddingBottom() + mLayout.getHeight());
}
long t2=System.currentTimeMillis();
Log.i("TEST", "onMeasure::"+(t2-t1));
}
public void setTextLayout(Layout layout) {
mLayout = layout;
requestLayout();
}}
你可以这样使用它:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
......
viewHolder.textView.setTextLayout(getLayout(mList.get(position)));
return convertView;
}
private final Map<String, Layout> mLayoutMap = new ConcurrentHashMap<String, Layout>();
private Layout getLayout(String str) {
Layout layout = mLayoutMap.get(str);
if (layout == null) {
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(20);
layout = new StaticLayout(str, textPaint, width, Alignment.ALIGN_CENTER,
1.0f, 0.0f, true);
mLayoutMap.put(str, layout);
}
return layout;
}
关于android - 如何使用 Instagram 的 "TextLayoutView"改进 Android 上的 TextView 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860276/