Android: 在自定义视图中获取父布局宽度以设置子宽度

Android: get parent layout width in custom view to set child width

我已经将 class 称为 ProgressButton,它扩展了 RelativeLayout。现在在主要 xml 中我添加了这个 class:

<com.tazik.progressbutton.ProgressButton
    android:id="@+id/pb_button"
    android:layout_width="200dp"
    android:layout_height="wrap_content"/>

如您所见,我添加了 android:layout_width="200dp",现在在 ProgressButton class 中,我想获得此尺寸以创建具有此尺寸的按钮:

public class ProgressButton extends RelativeLayout {

    private AppCompatButton button;

    public ProgressButton(Context context) {
        super(context);
        initView();
    }
    private void initView() {

        initButton();
    }

    private void initButton() {
        button = new AppCompatButton(getContext());
        LayoutParams button_params = new LayoutParams(????, ViewGroup.LayoutParams.WRAP_CONTENT);
        button_params.addRule(RelativeLayout.CENTER_IN_PARENT,RelativeLayout.TRUE);
        button.setLayoutParams(button_params);
        button.setText("click");
        addView(button);
    }

我想创建与 relativeLayout 大小完全相同的按钮,那么如何在我的自定义视图中获得 layout_width设置 button_params width?

now in ProgressButton class i want to get this size to create a button with this size

作为@MikeM。在评论中建议。它可以像给子视图一个 MATCH_PARENT 的宽度一样简单。见下文...

LayoutParams button_params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

有了它,您就不必担心实际尺寸,因为 MATCH_PARENT 会拉伸您的子视图以占据整个父视图的宽度...显然尊重边距和填充。

然而,如果您确实需要知道父级的宽度,您应该在 onMeasure 中查询。我强烈建议您尽可能远离 onMeasure,因为它有点复杂并且可能会占用您大量的开发时间。

无论哪种方式,在 onMeasure 你可以知道父视图想要给它的子视图什么测量,这是基于 space 可用于在父视图和布局参数中渲染指定...

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int childWidth = 0;

    if(widthSpecMode == MeasureSpec.AT_MOST){
        //The parent doesn't want the child to exceed "childWidth", it doesn't care if it smaller than that, just not bigger/wider
        childWidth = MeasureSpec.getSize(widthMeasureSpec);
    }
    else if(widthSpecMode == MeasureSpec.EXACTLY){
        //The parent wants the child to be exactly "childWidth"
        childWidth = MeasureSpec.getSize(widthMeasureSpec);
    }
    else {
        //The parent doesn't know yet what its children's width will be, probably
        //because it's still taking measurements
    }

    //IMPORTANT!!! set your desired measurements (width and height) or call the base class's onMeasure method. Do one or the other, NOT BOTH
    setMeasuredDimension(dimens, dimens);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

onMeasure 中添加一些 Log.d 调用,以便更好地了解正在发生的事情。请注意,此方法将被多次调用。

同样,这对于您的案例场景来说是不必要的矫枉过正。将 MATCH_PARENT 设置为按钮应该会产生您想要的结果