我在使用 ViewTreeObserver 时遇到了很大的困难。在一段不可预知的时间段内一切正常,然后监听器不再运行。这肯定是因为文档中写的:The returned ViewTreeObserver observer is not guaranteed to remain valid for the lifetime of this View 因此,我每次更改 View 时都会重做设置:
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();
最佳答案
通常我在重绘或更改布局之前将 addOnGlobalLayoutListener
监听器添加到我的 View (这可能发生在我第一次初始化 View 时或可能在更改其布局之前)并且在监听器中的第一件事我所做的是从 View 中删除监听器。
关于java - 一段时间后未调用 ViewTreeObserver 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9427682/