簡體   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