首页 > 代码库 > androi自定义自动换行的View(类似网页的标签Tag)

androi自定义自动换行的View(类似网页的标签Tag)

看来只有礼拜天才有时间写点博客啊,平时只能埋头苦干了。今天在公司加班,遇到一个需求,就是自动换行的TextView,有点像网页的tag标签,点击一下,就自动加上去了,不过这个是根据后台拿来的数据来显示多少个View,在网上找找,看见了许多,我自己也封装写一个吧,以便以后需要...开工

package com.woyou.ui.component;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.citaq.ideliver.R;

/**
 * 自动换行的View
 * 
 * @author shenzhou	2015年1月11日
 */
public class WordWrapView extends ViewGroup {
	private static final int PADDING_HOR = 10;// 水平方向padding
	private static final int PADDING_VERTICAL = 15;// 垂直方向padding
	private static final int SIDE_MARGIN = 10;// 左右间距
	private static final int TEXT_MARGIN = 10;

	public WordWrapView(Context context) {
		super(context);
	}

	public WordWrapView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public WordWrapView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int childCount = getChildCount();
		int autualWidth = r - l;
		int x = SIDE_MARGIN;// 横坐标开始
		int y = 0;// 纵坐标开始
		int rows = 1;
		for (int i = 0; i < childCount; i++) {
			View view = getChildAt(i);
			view.setBackgroundResource(R.drawable.shopdetail_keytag_bg);
			int width = view.getMeasuredWidth();
			int height = view.getMeasuredHeight();
			x += width + TEXT_MARGIN;
			if (x > autualWidth) {
				x = width + SIDE_MARGIN;
				rows++;
			}
			y = rows * (height + TEXT_MARGIN);
			if (i == 0) {
				view.layout(x - width - TEXT_MARGIN, y - height, x
						- TEXT_MARGIN, y);
			} else {
				view.layout(x - width, y - height, x, y);
			}
		}

	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int x = 0;// 横坐标
		int y = 0;// 纵坐标
		int rows = 1;// 总行数
		int specWidth = MeasureSpec.getSize(widthMeasureSpec);
		int actualWidth = specWidth - SIDE_MARGIN * 2;// 实际宽度
		int childCount = getChildCount();
		for (int index = 0; index < childCount; index++) {
			View child = (TextView) getChildAt(index);
			child.setPadding(PADDING_HOR, PADDING_VERTICAL, PADDING_HOR,
					PADDING_VERTICAL);
			child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
			int width = child.getMeasuredWidth();
			int height = child.getMeasuredHeight();
			x += width + TEXT_MARGIN;
			if (x > actualWidth) {// 换行
				x = width;
				rows++;
			}
			y = rows * (height + TEXT_MARGIN);
		}
		setMeasuredDimension(actualWidth, y);
	}

}
具体使用:

我的项目的布局文件太长了,我就说了

<com.woyou.ui.component.WordWrapView
	               style="@style/shopDetailTextStyle"
	               android:id="@+id/shopdetail_container"
	               android:layout_width="match_parent"
	               android:layout_height="wrap_content"
	               android:orientation="vertical"
	               android:paddingLeft="@dimen/dp20"
	               android:paddingRight="@dimen/dp20"
	               android:paddingTop="@dimen/dp10" />
把这段布局文件加到你要把文字自动换行的地方。java文件中的使用:

if ( !TextUtils.isEmpty(shopDetail.getInfo()) ) {
					infoLin.setVisibility(View.VISIBLE);
					//店铺关键字
					String key = shopDetail.getKey();
					strs = key.split("\\|");
					for (int i = 0; i < strs.length; i++) {
					      TextView textview = new TextView(mActivity);
					      textview.setText(strs[i]);
					      wordWrapView.addView(textview);
					}
					LogUtil.i(TAG, "tags:" + strs.toString());
前面还有找到控件什么的,我相信大家都是知道的。这只是核心代码,效果图如下:

技术分享

****************************************************************************************************************************

**********************介绍另外一种方法,是某个大神写的,不过没封装,供大家参考***********************************

****************************************************************************************************************************

 /** 标签之间的间距 px */  
    private final int itemMargins = (int) getContext().getResources().getDimension(R.dimen.dp15);  
    /** 标签的行间距 px */  
    private final int lineMargins = (int) getContext().getResources().getDimension(R.dimen.dp10);  
/**
	 * 加载店铺关键字
	 * @param tags
	 */
	private void loadShopKeys (String[] tags) {
		if ( tags == null )
			return;
		final int containerWidth = container.getMeasuredWidth() - container.getPaddingRight()  - container.getPaddingLeft();  
        final LayoutInflater inflater = mActivity.getLayoutInflater();  

        /** 用来测量字符的宽度 */  
        final Paint paint = new Paint();  
        final TextView textView = (TextView) inflater.inflate(R.layout.item_textviewtag_lv, null);  
        final int itemPadding = textView.getCompoundPaddingLeft() + textView.getCompoundPaddingRight();  
        final LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,  LayoutParams.WRAP_CONTENT);  
        tvParams.setMargins(0, 0, itemMargins, 0);  

        paint.setTextSize(textView.getTextSize());  
        LinearLayout layout = new LinearLayout(getContext());  
        layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));  
        layout.setOrientation(LinearLayout.HORIZONTAL);  
        container.addView(layout);  

        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);  
        params.setMargins(0, lineMargins, 0, 0);  

        /** 一行剩下的空间 **/  
        int remainWidth = containerWidth;  

        for (int i = 0; i < tags.length; ++i) {  
            final String text = tags[i];  
            final float itemWidth = paint.measureText(text) + itemPadding;  
            if (remainWidth > itemWidth) {  
                addItemView(inflater, layout, tvParams, text);  
            } else {  
                resetTextViewMarginsRight(layout);  
                layout = new LinearLayout(getContext());  
                layout.setLayoutParams(params);  
                layout.setOrientation(LinearLayout.HORIZONTAL);  

                /** 将前面那一个textview加入新的一行 */  
                addItemView(inflater, layout, tvParams, text);  
                container.addView(layout);  
                remainWidth = containerWidth;  
            }  
            remainWidth = (int) (remainWidth - itemWidth + 0.5f) - itemMargins;  
        }  
        resetTextViewMarginsRight(layout);  
    }  
	
	/***************** 将每行最后一个textview的MarginsRight去掉 *********************************/  
    private void resetTextViewMarginsRight(ViewGroup viewGroup) {  
        final TextView tempTx = (TextView) viewGroup.getChildAt(viewGroup.getChildCount() - 1);  
        tempTx.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
    }  
  
    private void addItemView(LayoutInflater inflater, ViewGroup viewGroup, android.widget.LinearLayout.LayoutParams tvParams, String text) {  
        final TextView itemTx = (TextView) inflater.inflate(R.layout.item_textviewtag_lv, null);  
        itemTx.setText(text);  
        viewGroup.addView(itemTx, tvParams);  
    }  
好了,到此结束了,屌丝要继续加班了,话说都好几天没打LoL,有点怀念了,等这段时间过了,本吊要撸到天明...



androi自定义自动换行的View(类似网页的标签Tag)