根据注释中的其他信息,即使可以在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);
}
}