我试图告诉我的标题尊重他旁边有一个日期,所以我想将他的宽度更改为背景的宽度,减去日期。但有时 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 之前它是相同的。
最佳答案
在您请求尺寸时,您的 View 还没有真正绘制出来。如果您的布局是静态的,最好在 XML 中进行,但如果它真的是动态的,那么您将需要使用 OnGlobalLayoutListener。等到 View 被第一次绘制然后调整它的大小。一些代码:
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();
}
});
关于java - 如何测量宽度和高度,然后在添加 View 之前更改参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29504678/