【发布时间】:2014-12-10 21:55:54
【问题描述】:
我试图在绘制之前获取 textView 高度,所以我使用其他问题中的 getViewTreeObserver 代码:
private TextView mTextView;
private int mTextViewHeight = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment, container, false);
mTextView = (TextView) mRootView.findViewById(R.id.text);
mTextView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
mTextViewHeight = mTextView.getHeight(); // Tried with getMeasured() too
if (Utils.hasJellyBean()) {
mTextView.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
mTextView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
}
});
使用此代码,我总是得到 mTextViewHeight = 0。我尝试过调试,并查看 OnGlobalLayoutListener 的入口点,线程永远不会访问“mTextViewHeight = mTextView.getHeight();”行。
谢谢!
编辑
答案很好,但我的错误是当我想在代码中使用 mTextViewHeight 时,这段代码是在进入监听器之前执行的,所以我得到的值是初始值。为了解决这个问题,我必须在侦听器中放入我想与 textView 高度一起使用的代码。
修复前:
private TextView mTextView;
private int mTextViewHeight = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment, container, false);
mTextView = (TextView) mRootView.findViewById(R.id.text);
mTextView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
mTextViewHeight = mTextView.getHeight(); // Tried with getMeasured() too
if (Utils.hasJellyBean()) {
mTextView.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
mTextView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
}
});
if(mTextViewHeight > maxHeightAllowed) {
mTextViewHeight /= 2;
} else {
String text = new String("");
for(int i = 0; i < mTextViewHeight.lenght(); i++)
text = text + getNextWord[i];
}
}
修复后
private TextView mTextView;
private int mTextViewHeight = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment, container, false);
mTextView = (TextView) mRootView.findViewById(R.id.text);
mTextView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
mTextViewHeight = mTextView.getHeight(); // Tried with getMeasured() too
if(mTextViewHeight > maxHeightAllowed) {
mTextViewHeight /= 2;
} else {
String text = new String("");
for(int i = 0; i < mTextViewHeight.lenght(); i++)
text = text + getNextWord[i];
}
if (Utils.hasJellyBean()) {
mTextView.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
mTextView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
}
});
}
【问题讨论】: