java - 如何测量宽度和高度,然后在添加 View 之前更改参数?

标签 java android android-linearlayout

我试图告诉我的标题尊重他旁边有一个日期,所以我想将他的宽度更改为背景的宽度,减去日期。但有时 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/

相关文章:

java - 使用 contentType application/json 发布正文后,Grails 未以 UTF-8 进行编码

java - lwjgl glDrawArrays 给出无效操作错误

Java 按钮创建无法正常工作

java - 有什么办法可以获取listView中的特定 View 吗?

Android:在哪里可以找到 xhdpi 菜单图标?

android - 如何在 MuPDF 中实现缩放放大镜

java - 生成类图的工具

android - 如何在屏幕上水平分割屏幕

android - Android中的线性布局和权重

java - Android:在Java/Kotlin中的ScrollView内部居中LinearLayout