自定义View使用继承FrameLayout实现布局明明在最上层但是实际渲染的时候跑到最下层去了
可能是由于绘制顺序的问题导致布局在最上层的View被覆盖到了最下层。在自定义View的绘制过程中,子View的绘制顺序是根据它们在父容器中的添加顺序来确定的。
要解决这个问题,可以尝试以下几种方法:
- 使用
bringToFront()方法将目标View带到最前面。在自定义View的代码中,通过调用bringToFront()方法将需要在最上层显示的View带到最前面。例如:
public class CustomView extends FrameLayout {
// ...
private void init() {
// ...
// 将目标View带到最前面
targetView.bringToFront();
}
}
- 在自定义View的布局文件中,将需要在最上层显示的View放在最后一个位置。在布局文件中,将目标View放在最后一个位置,这样它就会在绘制时最后被绘制,从而显示在最上层。
<CustomView>
<!-- 其他子View -->
<TargetView />
</CustomView>
- 重写
onLayout()方法来自定义子View的绘制顺序。在自定义View的代码中,重写onLayout()方法,并在其中按照需要的绘制顺序对子View进行布局。
public class CustomView extends FrameLayout {
// ...
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
View child = getChildAt(i);
child.layout(0, 0, right - left, bottom - top);
}
}
}
通过以上方法,可以确保目标View在绘制时显示在最上层
原文地址: https://www.cveoy.top/t/topic/ijLS 著作权归作者所有。请勿转载和采集!