2

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.

Diolor
  • 13,181
  • 30
  • 111
  • 179
  • Have you tried removing the `weight_sum`? I'm not sure but you may be better off letting the system handle that here. – codeMagic Jul 16 '14 at 15:27
  • @codeMagic Just tried. Didn't work (it gets inflated but stays "invisible"=0dp). – Diolor Jul 16 '14 at 15:30

2 Answers2

0

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);
AlonsoFloo
  • 505
  • 3
  • 10
  • Actually my parent is `LinearLayout` and the button a `RelativeLayout`. – Diolor Jul 16 '14 at 16:57
  • Ok, My bad, have you tried to add the `LinearLayout.LayoutParams` with the function `addView(bt, lp)` ? – AlonsoFloo Jul 16 '14 at 18:04
  • Just tried, unfortunately doesn't seem to work. Btw tip for the above: there is no constructor `RelativeLayout.LayoutParams(int, int, float)` because RelativeLayout does not accept weight_sum attribute. – Diolor Jul 16 '14 at 22:21
-1

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

Rujul1993
  • 1,631
  • 2
  • 10
  • 10