int currentLeft = offsetLeft; int size = mViews.size(); // 判断已经使用的宽度是否小于最大的宽度 float extra = 0; float widthAvg = 0; if (mMaxWidth > mUsedWidth) { extra = mMaxWidth - mUsedWidth; widthAvg = extra / size; }
for (int i = 0; i < size; i++) { View view = mViews.get(i); int viewWidth = view.getMeasuredWidth(); int viewHeight = view.getMeasuredHeight();
// 判断是否有富余 if (widthAvg != 0) { // 改变宽度,View的长度改变了,需要重新measure int newWidth = (int) (viewWidth + widthAvg + 0.5f); int widthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec .EXACTLY); int heightMeasureSpec = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec .EXACTLY); view.measure(widthMeasureSpec, heightMeasureSpec); viewWidth = view.getMeasuredWidth(); viewHeight = view.getMeasuredHeight(); }
// 布局 int left = currentLeft; int top = (int) (offsetTop + (mHeigth - viewHeight) / 2 + 0.5f); // int top = offsetTop; int right = left + viewWidth; int bottom = top + viewHeight; view.layout(left, top, right, bottom); currentLeft += viewWidth + mHorizontalSpace; } } }
privatevoidinitView() { setContentView(mScrollView = new ScrollView(this));
SpannableString title = new SpannableString("流式布局,热门标签"); title.setSpan(new ForegroundColorSpan(Color.WHITE),0,title.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(title);
mScrollView.setBackgroundColor(Color.parseColor("#eaeaea")); mScrollView.setVerticalScrollBarEnabled(false); mFlowLayout = new FlowLayout(this);
int padding = UIUtil.dip2px(15); mFlowLayout.setPadding(UIUtil.dip2px(10), padding, UIUtil.dip2px(10), padding); mFlowLayout.setSpace(UIUtil.dip2px(10), UIUtil.dip2px(15)); for (final String data : mData) {
TextView textView = new TextView(this); int tvPadding = UIUtil.dip2px(10); textView.setPadding(UIUtil.dip2px(15), tvPadding, UIUtil.dip2px(15), tvPadding); textView.setGravity(Gravity.CENTER); textView.setTextSize(16); textView.setText(data); textView.setTextColor(Color.WHITE);
Random random = new Random();//Math.random() int alpha = 255; int green = random.nextInt(190) + 30; int red = random.nextInt(190) + 30; int blue = random.nextInt(190) + 30; int argb = Color.argb(alpha, red, green, blue);
//设置shape GradientDrawable normalDrawable = new GradientDrawable(); normalDrawable.setCornerRadius(UIUtil.dip2px(6)); normalDrawable.setColor(argb);
GradientDrawable pressedDrawable = new GradientDrawable(); pressedDrawable.setColor(Color.DKGRAY); pressedDrawable.setCornerRadius(UIUtil.dip2px(5));
//设置选择器selector StateListDrawable stateListDrawable = new StateListDrawable(); stateListDrawable.addState(newint[]{android.R.attr.state_pressed}, pressedDrawable); stateListDrawable.addState(newint[]{}, normalDrawable);