【问题标题】:Inflate child with 0dp layout width & weight (programmatically)使用 0dp 布局宽度和重量来膨胀孩子(以编程方式)
【发布时间】:2014-07-16 15:23:56
【问题描述】:

简单:我想用 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。

【问题讨论】:

  • 你试过删除weight_sum吗?我不确定,但你最好让系统在这里处理。
  • @codeMagic 刚试过。没用(它会膨胀但保持“不可见”=0dp)。

标签: android android-view android-inflate


【解决方案1】:

您使用了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);

【讨论】:

  • 其实我的父母是LinearLayout,按钮是RelativeLayout。
  • 好吧,我的错,你有没有试过用函数addView(bt, lp)添加LinearLayout.LayoutParams?
  • 刚试过,不幸的是似乎不起作用。顺便说一句:没有构造函数RelativeLayout.LayoutParams(int, int, float) 因为RelativeLayout 不接受weight_sum 属性。
【解决方案2】:

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

bt.setVisibility(View.GONE);

您可以找到更多关于设置视图的信息here

【讨论】:

  • 这完全无关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多