我想告诉我的头衔,要尊重他旁边有个日期,因此我想将他的宽度改为背景的宽度,减去日期。但是有时getMeasuredWidth返回错误的值,或者只是返回0。如何执行此操作?每个项目都会调用此方法。
private void populateNewsItems(int pos, List<NewsItem> mFeedItems) {
NewsItem newsItem = mFeedItems.get(pos);
View newsContainer = getActivity().getLayoutInflater().inflate(R.layout.list_item_news, null);
TextView background = (TextView) newsContainer.findViewById(R.id.background);
TextView title = (TextView) newsContainer.findViewById(R.id.title);
TextView colorBlock = (TextView) newsContainer.findViewById(R.id.colorBlock);
TextView date = (TextView) newsContainer.findViewById(R.id.date);
TextView description = (TextView) newsContainer.findViewById(R.id.description);
title.setText(newsItem.getTitle());
date.setText(newsItem.getDate());
description.setText(newsItem.getDescription());
title.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
date.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
background.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
RelativeLayout.LayoutParams paramsTitle = (RelativeLayout.LayoutParams) title.getLayoutParams();
paramsTitle.width = background.getMeasuredWidth() - date.getMeasuredWidth();
title.setLayoutParams(paramsTitle);
Log.e("LOG", String.format("background width:%d ; date width:%d", background.getMeasuredWidth(), date.getMeasuredWidth()));
linearLayout.addView(newsContainer);
}
它读取的日期宽度绝对正确。但这可能是因为在填充textview之前是相同的。
在您要求尺寸时,实际上尚未绘制视图。如果您的布局是静态的,则最好在XML中完成,但是如果它是真正的动态,则您将需要使用OnGlobalLayoutListener来等待,直到首先绘制视图,然后再调整其大小。一些代码:
newsContainer.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// title.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
// date.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
// background.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
RelativeLayout.LayoutParams paramsTitle = (RelativeLayout.LayoutParams) title.getLayoutParams();
// paramsTitle.width = background.getMeasuredWidth() - date.getMeasuredWidth();
paramsTitle.width = background.getWidth() - date.getWidth();
title.setLayoutParams(paramsTitle);
title.requestLayout();
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句