在使用ViewTreeObserver时,我遇到了很大的困难。一切都能正常工作一段不可预测的时间,然后监听器就不再起作用了。这肯定是因为文档中写的东西:返回的ViewTreeObserver观察器不能保证在此视图的生命周期内保持有效。因此,每次更改视图时我都需要重新设置:
protected void shrinkToFit(final TextView t) {
if(vto==null||!vto.isAlive()){
vto = t.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
doAdjust(t);
}
});
}
}
以下是如何调用它的方法:
TextView t = (TextView) findViewById(R.id.maindesc);
t.setTextSize(Constants.MAINDESC_SIZE);
String todisp_1 = tarifreadtemp.area_desc + ":"
+ tarifreadtemp.area_tarifuserdesc;
shrinkToFit(t);
t.setText(todisp_1);
t.invalidate();