Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> androi自定義自動換行的View(類似網頁的標簽Tag)

androi自定義自動換行的View(類似網頁的標簽Tag)

編輯:關於Android編程

看來只有礼拜天才有時間寫點博客啊,平時只能埋頭苦干了。今天在公司加班,遇到一個需求,就是自動換行的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);
	}

}
具體使用:

我的項目的布局文件太長了,我就說了

把這段布局文件加到你要把文字自動換行的地方。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());
前面還有找到控件什麼的,我相信大家都是知道的。這只是核心代碼,效果圖如下:

\

<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKjwvcD4KPHA+KioqKioqKioqKioqKioqKioqKioqKr3pydzB7c3i0rvW1re9t6ijrMrHxLO49rTzyfHQtLXEo6yyu7n9w7u34tewo6y5qbTzvNKyzr+8KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKio8L3A+CjxwPioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKio8L3A+CjxwPjxwcmUgY2xhc3M9"brush:java;"> /** 標簽之間的間距 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,有點懷念了,等這段時間過了,本吊要撸到天明...



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved