String的截取和String的SpannableString的使用来丰富TextView的样式和减少布局的嵌套

来源:互联网 发布:xlsx软件 编辑:程序博客网 时间:2024/06/05 11:25

有时候,感觉总是去在网上查看别人的东西然后再自己用,其实这也没有什么,但是为什么不自己总结一下呢,这样也方便自己在以后的使用中很方便的拿来用

1、String的截取 
 源码如下:
 
    public int indexOf(String str) {        throw new RuntimeException("Stub!");    }    public int indexOf(String str, int fromIndex) {        throw new RuntimeException("Stub!");    }
String a="121";Log.i("aaa",a.indexOf("1")+"");
I/aaa: 0
 indexOf(String str, int fromIndex)
//返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索
System.out.println("hello world".indexOf('l',3));
I/System.out: 3
2、String.LastIndexOf
LastIndexOf (String)
报告指定的 String 在此实例内的最后一个匹配项的索引位置
LastIndexOf (Char, Int32)
报告指定 Unicode 字符在此实例中的最后一个匹配项的索引位置。该搜索从指定字符位置开始
LastIndexOf (String, Int32)
报告指定的 String 在此实例内的最后一个匹配项的索引位置。该搜索从指定字符位置开始
LastIndexOf (String, StringComparison)
报告指定字符串在当前 String 对象中最后一个匹配项的索引。一个参数指定要用于指定字符串的搜索类型
LastIndexOf (Char, Int32, Int32)
报告指定的 Unicode 字符在此实例内的子字符串中的最后一个匹配项的索引位置。搜索从指定字符位置开始,并检查指定数量的字符位置
String.LastIndexOf (String, Int32, Int32)
报告指定的 String 在此实例内的最后一个匹配项的索引位置。搜索从指定字符位置开始,并检查指定数量的字符位置
String.LastIndexOf (String, Int32, StringComparison)
报告指定字符串在当前 String 对象中最后一个匹配项的索引。参数指定当前字符串中的起始搜索位置,以及要用于指定字符串的搜索类型
LastIndexOf (String, Int32, Int32, StringComparison)

报告指定的 String 对象在此实例内的最后一个匹配项的索引位置。参数指定当前字符串中的起始搜索位置、要搜索的当前字符串中的字符数量,以及要用于指定字符串的搜索类型

String str ="报告指定 Unicode 字符在此实例中的最后一个指定匹配项的索引位置";

System.out.println(str.lastIndexOf("指定"));
System.out.println(str.lastIndexOf("指定",1));//0-1
System.out.println(str.lastIndexOf("指定",26));//0-26
System.out.println(str.lastIndexOf("指定",10));//0-10
02-23 16:46:58.801 26291-26291/? I/System.out: 25
02-23 16:46:58.801 26291-26291/? I/System.out: -1
02-23 16:46:58.801 26291-26291/? I/System.out: 25
02-23 16:46:58.801 26291-26291/? I/System.out: 2

3、String.Substring
Substring (Int32)
从此实例检索子字符串。子字符串从指定的字符位置开始
String.Substring (Int32, Int32)
从此实例检索子字符串。子字符串从指定的字符位置开始且具有指定的长度
String str ="报告指定 Unicode 字符在此实例中的最后一个指定匹配项的索引位置";
System.out.println(str.substring(10));
System.out.println(str.substring(10,15));
02-23 16:54:21.561 27609-27609/? I/System.out: de 字符在此实例中的最后一个指定匹配项的索引位置
02-23 16:54:21.561 27609-27609/? I/System.out: de 字符
4、SpannableString
参考

TextView使用SpannableString设置复合文本

http://www.cnblogs.com/jisheng/archive/2013/01/10/2854088.html
此处参考 

一些你需要知道的布局优化技巧

String text = String.format("¥%1$s 门市价:¥%2$s",18.6,22);
intz = text.lastIndexOf("门");
SpannableStringBuilder style = new SpannableStringBuilder(text);
style.setSpan(new AbsoluteSizeSpan(DisplayUtil.dip2px(mContext,14)),0,1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //字号
style.setSpan(new ForegroundColorSpan(Color.parseColor("#afafaf")),z, text.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //颜色
style.setSpan(new AbsoluteSizeSpan(DisplayUtil.dip2px(mContext,14)),z, text.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //字号
tv.setText(style);
希望对大家有帮助,不喜勿喷,谢谢!!!


1 0