繁体   English   中英

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

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

我已经创建了名为ProgressButton类,该类扩展了RelativeLayout 。现在在主xml中,我添加了此类:

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

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

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呢?

现在在ProgressButton类中,我想获得此尺寸以创建具有此尺寸的按钮

作为@MikeM。 在评论中建议。 就像给子视图一个宽度MATCH_PARENT 见下文...

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

有了这个位置,您就不必担心实际的大小,因为MATCH_PARENT会拉伸您的子视图以占据整个父对象的宽度,而……显然会忽略边距和填充。

但是,如果您确实需要知道父母的宽度,则应该在onMeasure查询。 我强烈建议您尽可能避免使用onMeasure因为它有点复杂,并且可能会花费很多开发时间。

无论哪种方式,您都可以在onMeasure中知道父视图要对其子视图进行哪些度量,这是基于可在父内部渲染的空间和指定的布局参数而定的。

@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设置为按钮应产生所需的结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM