简体   繁体   中英

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

Simple: I want to inflate parent with 1 child which has 0dp width.

Parent 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" >

The child class:

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);    
        }
    }
}

which uses the 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>

And the child is getting added by:

Parent.addView(new KeyButton(context) );

The problem is that android:layout_weight doesn't look to take action and the layout_width of the child stays at "0dp". If I change the width to 50dp I can see the child that has been correct inflated.

Also tried to add the parameters programmatically when getting added:

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

How can I inflate the child with 0dp/weight? Of course as you can see I have defined the weight_sum of the parent.

You have used a LinearLayout.LayoutParams but the parent of your button are a RelativeLayout .

Try this :

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

You can simply set the visibility property to gone or hidden by following code :

bt.setVisibility(View.GONE);

You can find more information about setting views here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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