【原创】在Android系统下实现抓词

  对于TextView显示的内容,通过点击屏幕,就能把当前显示的内容获取出来。以下的例子是通过判断空格来区分每个词,对于英文单词是适用的,如果想抓中文就得自己想办法了,当然也可以改变判断来抓词。

  实现代码主码有

TextPaint	paint = text.getPaint();
				float x, y;
				String str = text.getText().toString().replace(",", " ").replace("-", " ");
				String temp = " ";
				x = event.getX();
				y = event.getY();
				for (int i = 0; i < str.length(); i++) {
					char ch = str.charAt(i);
					if (ch == ' ') {
						temp = temp + " " + i;
					}
				}
				temp = temp + " " + str.length();
				String[] nums = temp.trim().split(" ");// 获取空格位置
				String subArg[] = str.split(" ");// 获取无空格的字符
				if (subArg.length == 1) {
					System.out.println(new String(subArg[0]));
				} else {
					for (int i = 1; i < subArg.length; i++) {
						if (x <= (paint.measureText(str.substring(0, Integer.parseInt(nums[i]))))&& x > (paint.measureText(str.substring(0,Integer.parseInt(nums[i - 1]) + 1)))) {
							System.out.println(new String(subArg[i]));
						} else if (x <= (paint.measureText(str.substring(0,Integer.parseInt(nums[0]))))) {
							System.out.println(new String(subArg[0]));
						}
					}
				}
主要思路是按照空格的位置和点击屏幕的x坐标来判断。
posted on 2011-07-12 11:33  月vs枫  阅读(406)  评论(1编辑  收藏  举报