[英]How to make invisible a partially visible view inside LinearLayout?
假设我们有一个简单的LinearLayout,其垂直方向的尺寸为width:100dp,height:100dp
在布局内有10个TextView(宽度:fill_parent,高度:wrap_content,max_lines = 1,scroll_horizontally = true,ellipsize = end)。 每个文本视图都是可见的,并填充有14dp文本“ What a text”。 android设备的最终密度无关紧要。 大多数TextView将正确显示,但是由于强制使用布局大小,其中一些将不可见或被剪切。
目标是:检测裁剪的视图并将其隐藏。
我尝试使用自定义的LinearLayout子类,其中在布局阶段会测量每个子视图并将其与目标大小进行比较。 问题是度量调用会更改内部视图度量值-如果child不是一个简单视图而是一个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);
}
}
}
}`
试试下面的代码。 它应该可以,但是我还没有测试,所以我可能是错的:
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;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.