搞乱边距以实现绝对定位是错误的。如果你将来需要边距,这种方法就无法扩展。
从Android中偷取代码,进行修改,然后使用你的“未弃用”的绝对布局。
AbsoluteLayout被弃用是因为他们不想支持它,而不是因为它不起作用。
别管他们,他们的布局不能满足我们的需求,那么他们推荐什么?自定义视图。
所以这里有一个(重构后,不带样式(呕吐)支持):
package com.example;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RemoteViews.RemoteView;
@RemoteView
public class DCAbsoluteLayout extends ViewGroup {
int mPaddingLeft, mPaddingRight, mPaddingTop, mPaddingBottom;
public DCAbsoluteLayout(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
int maxHeight = 0;
int maxWidth = 0;
measureChildren(widthMeasureSpec, heightMeasureSpec);
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
int childRight;
int childBottom;
DCAbsoluteLayout.LayoutParams lp
= (DCAbsoluteLayout.LayoutParams) child.getLayoutParams();
childRight = lp.x + child.getMeasuredWidth();
childBottom = lp.y + child.getMeasuredHeight();
maxWidth = Math.max(maxWidth, childRight);
maxHeight = Math.max(maxHeight, childBottom);
}
}
maxWidth += mPaddingLeft + mPaddingRight;
maxHeight += mPaddingTop + mPaddingBottom;
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, 0),
resolveSizeAndState(maxHeight, heightMeasureSpec, 0));
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0);
}
@Override
protected void onLayout(boolean changed, int l, int t,
int r, int b) {
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
DCAbsoluteLayout.LayoutParams lp =
(DCAbsoluteLayout.LayoutParams) child.getLayoutParams();
int childLeft = mPaddingLeft + lp.x;
int childTop = mPaddingTop + lp.y;
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof DCAbsoluteLayout.LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
public int x;
public int y;
public LayoutParams(int width, int height, int x, int y) {
super(width, height);
this.x = x;
this.y = y;
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
}
一般来说,Android UI 是一个噩梦。考虑使用 webview 来完成整个项目。就系统的工作而言,“还好”,但是那个 UI 真是一团糟。
HTML 一直是样式和动态 UI 内容的首选。没有什么能与它相提并论,但自定义绘制的 UI(在性能方面)。
RelativeLayout
,但是当我将视图添加到此自定义视图时,它不会出现,因此子视图未显示。 - user25