【问题标题】:Child view doesn't obtain size values子视图不获取大小值
【发布时间】:2017-10-31 18:28:46
【问题描述】:

我有一个简单的类AppPopup,它扩展了 FrameLayout。该类膨胀其内容并将其存储在内容变量中。我需要内容位于弹出窗口视图的中心。为了测量内容,我覆盖了 onMeasure,但高度/在这个方法中内容的宽度等于-1

public class AppPopup extends FrameLayout {
    private View content;
    private View bg;
    public AppPopup(@NonNull Context context) {
        super(context);
    }

    public AppPopup(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setLayout(int resId) {
        LayoutInflater li=LayoutInflater.from(getContext());
        bg=li.inflate(R.layout.popup_bg_fade,null);
        content=li.inflate(resId,null);
    }
    public void show() {
        addView(bg);
        addView(content);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        Log.d("layout",content.getLayoutParams().width+","+content.getLayoutParams().height+","+(content.getParent()==this)); -1,-1,true
        content.setX(widthSize/2-content.getLayoutParams().width/2);
        content.setY(heightSize/2-content.getLayoutParams().height/2);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.d("layout",content.getLayoutParams().width+","+content.getLayoutParams().height+","+(content.getParent()==this)); //-1,-1,true
    }
}

我在父视图中调用它:

AppPopup popup=new AppPopup(this);
root.addView(popup);
popup.setLayout(R.layout.gameover_popup1);
popup.show();

在 onLayout 内大小也等于 -1。但我可以在屏幕上以正确的大小看到我的视图。 我知道我遗漏了一些简单的东西,但不知道是什么。

【问题讨论】:

    标签: android measurement


    【解决方案1】:

    int widthSize = MeasureSpec.getSize(widthMeasureSpec);可以是 WRAP_CONTENT 或 MATCH_PARENT。

    你可以得到just(仅在super.onMeasure之后工作,因为它在完成后设置了Measured):

    int widthSize = getMeasuredWidth();
    int heightSize = getMeasuredHeight();
    

    对于膨胀后的子宽度,您可以调用 AFTER super.onLayout child.getMeasuredWidth();

    【讨论】:

    • 我的问题是如何获取子视图的大小(内容变量)。我需要它来对齐容器视图中的内容。检测容器大小没有问题。
    • 在onLayout之后可以调用child.getMeasuredWidth();
    • 它仍然返回容器大小。由于某种原因,当我将内容视图添加到视图层次结构时,它会扩展到全屏,就像它具有 match_parent 大小一样,但这不是真的。它具有固定大小。无论如何我设法解决了通过将内容包装到额外的 FrameLayout 并将 wrap_content 设置为此根布局。
    猜你喜欢
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    相关资源
    最近更新 更多