android获取另一个layout布局,android - 以FrameLayout作为根布局,在另一个视图的顶部添加具有X,Y偏移的视图 - 堆栈内存溢出...

根据注释中的其他信息,即使可以在FrameLayout重叠不同的布局,这些布局也只能放置自己的子级。 RelativeLayout无法将其子视图之一相对于其他同级或父Layout中的视图定位。

可行的方法是平整Layouts的层次结构,将根布局设置为RelativeLayout或ConstraintLayout 。

ConstraintLayout在定位视图方面更灵活,但也更难学习。

在这里,我留下了一种替代方法,可以将RelativeLayout用作根视图。 要查看的重要项目是LayoutParams的设置,有时可能会引起混淆。

LayoutParams在子视图上设置,但是使用的类取决于父视图。

还要记住,要保持页边空白独立显示,您需要将dp转换为像素(为简单起见,我没有这样做,但是在SO中有一些示例说明如何做到这一点)。

它还使用View.generteViewId()获取动态创建的视图的ID。

为简单起见,我在XML中包含了参考View ,但是我也可以动态创建。

布局

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/rlContainer"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:id="@+id/tvCenterText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Texto estatico"

android:layout_centerInParent="true"/>

主要活动

public class DynamicViewsActivity extends AppCompatActivity {

RelativeLayout rlContainer;

TextView centerText;

@Override

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_dynamicviews);

rlContainer = findViewById(R.id.rlContainer);

centerText = findViewById(R.id.tvCenterText);

placeTextRelativeToBottomLeftOfViewAtXY(rlContainer, centerText, 100,10, "Hola");

}

public void placeTextRelativeToBottomLeftOfViewAtXY(final RelativeLayout layout, View component, int x, int y, String text) {

final TextView textView = new TextView(this);

textView.setId(View.generateViewId());

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

params.setMargins(x, y, x,y);

params.addRule(RelativeLayout.LEFT_OF, component.getId());

params.addRule(RelativeLayout.ALIGN_BASELINE, component.getId());

textView.setLayoutParams(params);

textView.setText(text);

layout.addView(textView);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值