您的位置:首页 > 其它

如何省略显示过多的child views

2016-03-23 19:37 417 查看

实现过多子view的省略显示

多个icon在一个父容器内(LinearLayout),过多icon导致无法全部显示时加入省略号的实现方案:

布局为大容器icon_area包含icon的父容器以及省略号的image view,将image view的引用给到icon对象。而自定义的icon的父容器IconMerger,负责计算child view是否超过最最大宽度,然后显示或隐藏省略号

布局xml如下:

<LinearLayout
android:id="@+id/icon_area"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<IconMerger
android:id="@+id/notificationIcons"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:gravity="center_vertical"
android:orientation="horizontal" />

<ImageView
android:id="@+id/moreIcon"
android:layout_width="13dp"
android:layout_height="match_parent"
android:src="@drawable/stat_notify_more"
android:visibility="gone" />

</LinearLayout>


自定义IconMerger实现:

public class IconMerger extends LinearLayout {
private static final String TAG = "IconMerger";
private static final boolean DEBUG = false;

private int mNotificationIconSize;
private View mMoreView;

public IconMerger(Context context, AttributeSet attrs) {
super(context, attrs);

mNotificationIconSize = context.getResources().getDimensionPixelSize(
R.dimen.status_bar_notification_icon_size);

}

public void setOverflowIndicator(View v) {
mMoreView = v;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// we need to constrain this to an integral multiple of our children
int width = getMeasuredWidth();
//计算容器大小时,保证宽度恰好容纳整数个icon
setMeasuredDimension(width - (width % mNotificationIconSize), getMeasuredHeight());
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
//onlayout时检测宽度是否超出
checkOverflow(r - l);
}

private void checkOverflow(int width) {
if (mMoreView == null) return;

final int N = getChildCount();
int visibleChildren = 0;
for (int i=0; i<N; i++) {
//记录所有非gone的icon数目
if (getChildAt(i).getVisibility() != GONE) visibleChildren++;
}
final boolean overflowShown = (mMoreView.getVisibility() == View.VISIBLE);
// let's assume we have one more slot if the more icon is already showing
if (overflowShown) visibleChildren --;
final boolean moreRequired = visibleChildren * mNotificationIconSize > width;
if (moreRequired != overflowShown) {
post(new Runnable() {
@Override
public void run() {
mMoreView.setVisibility(moreRequired ? View.VISIBLE : View.GONE);
}
});
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: