现在的位置: 首页 > 综合 > 正文

android sina 微博表情功能的实现

2013年12月06日 ⁄ 综合 ⁄ 共 2112字 ⁄ 字号 评论关闭

表情为本地表情,把所有的表情图片装载到gridview里面。然后在gridview的点击事件里做如下处理。

@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		if(mEditText == null) return;
		
		String content = mEditText.getText().toString().trim() + emotionNames[index];
		if(TextUtils.isEmpty(content)) return;
		
		Log.d(TAG, "SinaEmotionView: content = " + content);
		
		boolean isLeft = true;	//应该出现哪一边的括号
		List<Integer> leftBracketAt = new ArrayList<Integer>();
		List<Integer> rightBracketAt = new ArrayList<Integer>();
		
		char[] c_content = content.toCharArray();
		for(int i = 0; i < c_content.length; i++){
			if('[' == c_content[i]){
//				Log.d(TAG, "left ------- " + i);
				if(!isLeft){	//如果不该出现左括号时,出现了。则覆盖上一个。
					leftBracketAt.remove(leftBracketAt.size() - 1);
				}
				leftBracketAt.add(new Integer(i));
				isLeft = false;
			}else if(']' == c_content[i]){
//				Log.d(TAG, "right ------- " + i);
				if(isLeft){
					rightBracketAt.remove(leftBracketAt.size() - 1);
				}
				rightBracketAt.add(new Integer(i));
				isLeft = true;
			}
		}
		
		SpannableString spannable = new SpannableString(content);
		//获得左右[]位置链表长度小的链表的长度//因为用户也有可能输入"[" 或者 "]"
		int miniSize = leftBracketAt.size() <= rightBracketAt.size() ? leftBracketAt.size() : rightBracketAt.size();
		for(int j = 0; j < miniSize; j++){
			int leftAt = leftBracketAt.get(j);
			int rightAt = rightBracketAt.get(j) + 1;
			while(leftAt >= rightAt){
				rightBracketAt.remove(j);
				rightAt = rightBracketAt.get(j);
//				Log.d(TAG, "while ---- ");
			}
			String name = content.substring(leftAt, rightAt);
//			Log.d(TAG, "name ---- " + name + ".");
			
			//查询name是不是表情的name
			int pos = emotionNamePos(name);
			if(-1 != pos){
				//把文字替换成图片来显示
				Drawable drawable = getResources().getDrawable(emotionIconIds[pos]);
				drawable.setBounds(0, 10, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()+10);
				ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
				spannable.setSpan(span, leftAt, rightAt, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
			}
		}
		
		mEditText.setText(spannable);
		
		//设置光标位置到最后
		mEditText.requestFocus();
		mEditText.setSelection(content.length());
	}
	

其中,

mEditText是要显示表情及微博文本内容的EditText控件

emotionIconIds是表情图片id的int型数组

emotionNames是表情对应的文字(如,"[哈哈]")的一个字符串数组

/**
	 * 查询一个字符串是不是一个表情的名字,
	 * 如果是,则返回位置,如果不是则返回-1;
	 * @param name
	 * @return
	 */
	private int emotionNamePos(String name){
		if(name == null) return -1;
		for(int i = 0; i < emotionNames.length; i++){
			if(name.equals(emotionNames[i])) return i;
		}
		return -1;
	}

抱歉!评论已关闭.