假设我们有一个简单的LinearLayout,其垂直方向的大小为宽度:100dp,高度为:100dp
在布局中有10个TextViews(width:fill_parent,height:wrap_content,max_lines = 1,scroll_horizontally = true,ellipsize = end)。每个文本视图都可见,并填充14dp文本“What a text”。 Android设备的最终密度无关紧要。大多数TextView都会正确显示,但由于强制布局大小,其中一些将不可见或被剪裁。
目标是:检测剪切的视图,并隐藏它们。
我尝试使用自定义LinearLayout子类,其中在布局阶段测量每个子视图并与目标大小进行比较。问题是测量调用,更改内部视图测量值 - 如果子视图不是简单视图而是ViewGroup - 它不会被正确显示。据我所知 - 在测量阶段之后 - 应该有布局阶段。但一切都发生在自定义LinearLayout的布局阶段。
修改
好的,简化我的问题 - 我希望有一个LinearLayout或一般来说 - 一个ViewGroup,它不会绘制部分可见的孩子。
自定义布局类代码:
public final class ClipAwareLinearLayout extends LinearLayout
{
public ClipAwareLinearLayout(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ClipAwareLinearLayout(Context context)
{
super(context);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
super.onLayout(changed, l, t, r, b);
final int width = r - l;
final int height = b - t;
final int count = getChildCount();
final int msWidth = MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST);
final int msHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST);
View child;
int measuredHeight;
int childHeight;
for (int i = 0; i < count; ++i)
{
child = getChildAt(i);
if (child != null)
{
childHeight = child.getHeight();
child.measure(msWidth, msHeight);
measuredHeight = child.getMeasuredHeight();
final boolean clipped = (childHeight < measuredHeight);
child.setVisibility(clipped ? View.INVISIBLE : View.VISIBLE);
}
}
}
}`
答案 0 :(得分:0)
尝试以下代码。它应该工作,但我没有测试,所以我可能是错的:
class ClippedLinear extends LinearLayout {
public ClippedLinear(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean status = false;
for (int i = getChildCount() - 1; i > 0; i--) {
if (status) {
continue;
}
final View child = getChildAt(i);
final int childHeight = child.getMeasuredHeight();
if (childHeight == 0) {
child.setVisibility(View.GONE);
} else {
child.measure(widthMeasureSpec, heightMeasureSpec);
if (childHeight < child.getMeasuredHeight()) {
child.setVisibility(View.GONE);
}
status = true;
}
}
}
}