繁体   English   中英

使用0dp布局宽度和重量为孩子充气(以编程方式)

[英]Inflate child with 0dp layout width & weight (programmatically)

简单:我想给1个宽度为0dp的孩子充气。

父XML:

<com.example.KeyPad      // extend LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="4"     // for the children
    android:layout_weight="1" // this is for its parent
    android:clickable="true"
    android:background="@color/MidnightBlue" >

子班:

public class KeyButton extends RelativeLayout implements View.OnClickListener{    
    public KeyButton(Context c ) {
        super(c);
        RelativeLayout v = (RelativeLayout) LayoutInflater.from(c).inflate(R.layout.key_button, this, true);    
        }
    }
}

使用R.layout.key_button xml:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:background="@android:color/holo_red_dark"
    android:layout_height="wrap_content">

    <TextView ... />

</RelativeLayout>

然后通过以下方式添加孩子:

Parent.addView(new KeyButton(context) );

问题是android:layout_weight似乎不采取任何措施,并且子代的layout_width保持为“ 0dp”。 如果将宽度更改为50dp,我可以看到正确膨胀的孩子。

还尝试在添加时以编程方式添加参数:

KeyButton bt = new KeyButton(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1.0f);
bt.setLayoutParams(lp);
Parent.addView(bt);

如何为孩子充气0dp /体重? 当然,如您所见,我已经定义了父级的weight_sum。

您使用了LinearLayout.LayoutParams但是按钮的父级是RelativeLayout

尝试这个 :

KeyButton bt = new KeyButton(context);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(0, RelativeLayout.LayoutParams.WRAP_CONTENT,1.0f);
Parent.addView(bt, lp);

您可以通过以下代码简单地将可见性属性设置为走或隐藏:

bt.setVisibility(View.GONE);

您可以在此处找到有关设置视图的更多信息

暂无
暂无

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

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