Android RelativeLayout 参数被忽略

标签 android android-relativelayout android-custom-view

我遇到了一个奇怪的问题: 我有一个从 RelativeLayout 扩展的类。

然后我想像这样添加两个 View :

mButtonTip = new ButtonTip(context, attrs);
mToolTip = new ToolTip(context, attrs);

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);

RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params2.addRule(RelativeLayout.ALIGN_BOTTOM, mToolTip.getId());

addView(mToolTip, params1);
addView(mButtonTip, params2);

不幸的是,mToolTip View 已正确放置,但 mButtonTip 不会从布局的左下角移动。

您知道为什么 mButtonTip View 会忽略我刚刚设置的布局参数吗?

最佳答案

好吧,对于那些可能遇到同样问题的人,我找到了解决方案:

我需要像那样显式设置不同 View 的 id :

mButtonTip = new ButtonTip(context, attrs);
mButtonTip.setId(1);

mToolTip = new ToolTip(context, attrs);
mToolTip.setId(2);

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);

RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params2.addRule(RelativeLayout.ALIGN_BOTTOM, mToolTip.getId());

addView(mToolTip, params1);
addView(mButtonTip, params2);

关于Android RelativeLayout 参数被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15760649/

相关文章:

android - 2.2中RelativeLayout中的TextView项重叠; 1.6没问题

android - 如何从自定义 View 访问宿主 fragment 的生命周期范围?

android - 以编程方式创建多行 EditText

java - setPixel 在位图周围留下黑色边框,如何避免?

android - 谷歌玩游戏 : messaging other players

java - 如何从房间数据库读取所有值并显示到recyclerview中?

android - 复制API 19之前RelativeLayout.LayoutParams的规则

安卓用户界面 : Align button at bottom of scrollview inside tabs

android - 如何正确地将自定义 View 添加到 Activity

android - 奇怪的 View.getHitRect() 行为