我想将视图放置在现有视图之上。我定位的视图位于LinearLayout内部,该外观位于FrameLayout中。
我正在考虑使用RelativeLayout做到这一点,因为我已经使其部分工作了。我想将新视图对齐到左下角或左上角(作为原点),然后将X和Y偏移到我指定的某个精确值。
如何实现?
这是主意:
public static void placeTextRelativeToBottomLeftOfViewAtXY(final FrameLayout layout, View component, int x, int y, String text) {
final TextView textView = new TextView(getContext());
textView.setId((int)System.currentTimeMillis());
final RelativeLayout relativeLayout = new RelativeLayout(getContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.setMargins(x, y, 0,0);
params.addRule(RelativeLayout.LEFT_OF, component.getId());
relativeLayout.setLayoutParams(params);
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
textView.setText("+500 points!");
textView.bringToFront();
relativeLayout.addView(textView, params);
layout.addView(relativeLayout);
}
答案 0 :(得分:1)
基于注释中的其他信息,即使可以在FrameLayout
中重叠不同的布局,这些布局也只能放置自己的子级。
RelativeLayout
将无法将其子视图之一相对于其他同级或父布局中的视图放置。
可行的方法是平整布局的层次结构,将根布局设置为RelativeLayout
或ConstraintLayout
。
ConstraintLayout
在定位视图方面更为灵活,但也更加难以学习。
在这里,我要离开一个替代方案,以将RelativeLayout
用作根视图。要查看的重要项目是LayoutParams
的设置,有时可能会引起混淆。
LayoutParams
在子视图上设置,但是使用的类取决于父视图。
还请记住,要保持页边空白独立显示,您需要将dp转换为像素(为简单起见,我没有这样做,但是在SO中有一些有关如何执行此操作的示例)。
它还使用View.generteViewId()
获取动态创建的视图的ID。
为简单起见,我在xml中包含了引用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);
}
}