1. 程式人生 > >Android 搜尋到的關鍵字改變顏色

Android 搜尋到的關鍵字改變顏色

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mAnchors.size();
		}

		@Override
		public Object getItem(int position) {
			return mAnchors.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			LayoutInflater mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			View mView = mInflater.inflate(R.layout.cell_anchor, arg2, false);
			ImageView mImage = (ImageView) mView
					.findViewById(R.id.search_anchor_image);
			TextView mTextName = (TextView) mView
					.findViewById(R.id.search_anchor_name);
			TextView mTextId = (TextView) mView
					.findViewById(R.id.search_anchor_id);
			
			int chageTextColor;
			ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue));
			LiveRoom anchor = mAnchors.get(arg0);

			SpannableStringBuilder builder = new SpannableStringBuilder(
					anchor.anchorName);
			chageTextColor = anchor.anchorName.indexOf(mSearchText);
			if (chageTextColor != -1) {
				builder.setSpan(redSpan, chageTextColor, chageTextColor
						+ mSearchText.length(),
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				mTextName.setText(builder);
			} else
				mTextName.setText(anchor.anchorName);

			SpannableStringBuilder builder1 = new SpannableStringBuilder(
					String.valueOf(anchor.anchorId));
			chageTextColor = String.valueOf(anchor.anchorId).indexOf(
					mSearchText);
			if (chageTextColor != -1) {
				builder1.setSpan(redSpan, chageTextColor, chageTextColor
						+ mSearchText.length(),
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				mTextId.setText(builder1);
			} else
				mTextId.setText(String.valueOf(anchor.anchorId));
			return mView;
		}

	}