基于注释中的附加信息,即使有可能在
FrameLayout
A
RelativeLayout
无法相对于其他同级或父级布局中的视图定位其子视图之一。
方法是使布局的层次结构更平坦,将根布局设置为
或者
ConstraintLayout
.
在定位观点上比较灵活,但学习起来也比较困难。
在这里,我留下了一个替代使用
相对布局
LayoutParams
这有时有点令人困惑。
布局参数
在子视图上设置,但使用的类取决于父视图。
View.generteViewId()
获取动态创建的视图的id。
为了简单起见,我加入了参考资料
View
但我也可以动态创建。
布局
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rlContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvCenterText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Texto estatico"
android:layout_centerInParent="true"/>
</RelativeLayout>
主要活动
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);
}
}