`
marine8888
  • 浏览: 540448 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

删除TextView中无法正常显示的小方格(转载)

阅读更多

  TextView中的小方格

最近要写一个小程序,要在TextView里面显示中文,可是出现好多小方格,出现这种情况的原因是TextView并不支持这些字符。

这有可以分成两种情况,一是字库里不包含的字,通常是一些特别冷僻的字。这种对我们写程序来说是无能为力的,只能靠用户自己去更新系统的字库。第二种情况是有一些特殊的字符,比如'\r'(回车),TextView不能识别。所以解决办法就是把它过滤掉。

这里提供两种方法:

一种很容易想到,就是一个一个字符去比较,等于'\r'就delete掉。

view plaincopy to clipboardprint?
String str;  
StringBuffer buf = new StringBuffer(str);  
for(int i=0;i<buf.length();i++)  
    if(buf.charAt(i) == '\r')  
        buf = buf.deleteCharAt(i);  
str = buf.toString(); 
String str;
StringBuffer buf = new StringBuffer(str);
for(int i=0;i<buf.length();i++)
    if(buf.charAt(i) == '\r')
        buf = buf.deleteCharAt(i);
str = buf.toString();

还有一种方法是用TextView 的setTransformationMethod(TransformationMethod method)把所有字库不支持的char都过滤掉。

TransformationMethod只是一个接口,如果要实现替换操作,最方便的做法是继承抽象类ReplacementTransformationMethod,ReplacementTransformationMethod实现了TransformationMethod的方法,并提供了两个抽象函数。getOriginal()返回的是需要被替换的char[],getReplacement()返回的是替换后的char[]。

这里我用空格替换回车,3替换2,注意它们是一一对应的。

view plaincopy to clipboardprint?
private class MyTransformationMethod extends ReplacementTransformationMethod{  
        @Override 
        protected char[] getOriginal() {  
            char[] original={'\r','2'};  
            return original;  
        }  
        @Override 
        protected char[] getReplacement() {         
            char[] replacement={' ','3'};  
            return replacement;  
        }  
         
    } 
private class MyTransformationMethod extends ReplacementTransformationMethod{
        @Override
        protected char[] getOriginal() {
            char[] original={'\r','2'};
            return original;
        }
        @Override
        protected char[] getReplacement() {      
            char[] replacement={' ','3'};
            return replacement;
        }
      
    }

然后只要在开始的地方调用一次textView.setTransformationMethod(new MyTransformationMethod())就可以了。

显然,后面一种方法更好一些。


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Seaside_Boy/archive/2010/01/20/5218536.aspx

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics