Android - Context中的getText(int resId)方法和getString(int resId)方法的区别

Android开发中,经常在Activity中使用getText(int resId)和getString(int resId)这两个方法,那么这两个方法有什么区别和联系呢?

这两个方法的参数都是资源ID,区别在于getText(int resId)返回的是一个CharSequence,而getString(int resId)返回的是一个String。源代码如下:

getText(int resId):

 /**
  * Return a localized, styled CharSequence from the application‘s package‘s
  * default string table.
  *
  * @param resId Resource id for the CharSequence text
  */
 public final CharSequence getText(int resId) {
     return getResources().getText(resId);
 }

getString(int resId):

/**
  * Return a localized string from the application‘s package‘s
  * default string table.
  *
  * @param resId Resource id for the string
  */
 public final String getString(int resId) {
     return getResources().getString(resId);
 }

可以看到,他们在各自的内部又调用了Resources类的getText(int id)和getString(int id)方法,那么我们就再看一下Resources类中的这两个方法是怎么写的:

Resources类中的getText(int id):

 /**
   * Return the string value associated with a particular resource ID.  The
   * returned object will be a String if this is a plain string; it will be
   * some other type of CharSequence if it is styled.
   * {@more}
   *
   * @param id The desired resource identifier, as generated by the aapt
   *           tool. This integer encodes the package, type, and resource
   *           entry. The value 0 is an invalid identifier.
   *
   * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
   *
   * @return CharSequence The string data associated with the resource, plus
   *         possibly styled text information.
   */
  public CharSequence getText(int id) throws NotFoundException {
      CharSequence res = mAssets.getResourceText(id);
      if (res != null) {
          return res;
      }
      throw new NotFoundException("String resource ID #0x"
                                  + Integer.toHexString(id));
  }

Resources类中的getString(int id):

/**
   * Return the string value associated with a particular resource ID.  It
   * will be stripped of any styled text information.
   * {@more}
   *
   * @param id The desired resource identifier, as generated by the aapt
   *           tool. This integer encodes the package, type, and resource
   *           entry. The value 0 is an invalid identifier.
   *
   * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
   *
   * @return String The string data associated with the resource,
   * stripped of styled text information.
   */
  public String getString(int id) throws NotFoundException {
      CharSequence res = getText(id);
      if (res != null) {
          return res.toString();
      }
      throw new NotFoundException("String resource ID #0x"
                                  + Integer.toHexString(id));
  }

看到这里我想大家就都明白了,Resources类的中getString(int id)方法其实就是调用了Resources类的getText(int id)方法后,多做了一个toString()处理,那么也就是说,我们要讨论的问题的结论就可以理解为:Context类中的getString(int resId)==getText(int resId).toString()。

更直观一点,我们来做个小demo:

首先,在Strings中定义两个string资源:

<string name="get_text"><b>getText</b></string>
<string name="get_string"><b>getString</b></string>

接着,在layout文件中定义两个TextView,分别是textView1和textView2(代码省略)。

最后,分别使用getText(int resId)和getString(int resId)获取上面两个资源,并在textView1和textView2中显示:

CharSequence charSequence = getText(R.string.get_text);
String str = getString(R.string.get_string);
((TextView)findViewById(R.id.textView1)).setText(charSequence);
((TextView)findViewById(R.id.textView2)).setText(str);

结果一目了然:

时间: 2024-08-05 03:49:03

Android - Context中的getText(int resId)方法和getString(int resId)方法的区别的相关文章

Servlet的Service方法和doget 和 dopost方法的区别,常见的错误解析

package com.sxt.in; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Service方法和doget 和 dopost方

jQuery.extend()方法和jQuery.fn.extend()方法

jQuery.extend()方法和jQuery.fn.extend()方法源码分析 这两个方法用的是相同的代码,一个用于给jQuery对象或者普通对象合并属性和方法一个是针对jQuery对象的实例,对于基本用法举几个例子: html代码如下: <!doctype html> <html> <head> <title></title> <script src='jquery-1.7.1.js'></script> <

Scanner中next()和nextline()读取字符串方法和区别

在实现字符窗口的输入时,我个人更喜欢选择使用扫描器Scanner,它操作起来比较简单.在写作业的过程中,我发现用Scanner实现字符串的输入有两种方法,一种是next(),一种nextLine(),但是这两种方法究竟有什么区别呢?我查了一些资料总结了一下,希望对大家有所帮助- next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键.Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键.Tab键或E

android studio中导入第三方jar包和第三方库文件的方法

一.导入第三方jar包的方法 其实较为简单,以下步骤: 1>在工程的libs下面放置需要导入的jar包 2>在导入的jar包右键,选择"add as library" 3>这时候就能够在app下面的build.gradle中发现多了如下说明:"compile XXXX",说明导入jar文件成功了. 二.导入第三方类库文件 相对而言,其实就是将之前的Eclipse的project或者module转化成android studio下的可执行的proje

Java中创建对象的5种方式 &amp;&amp;new关键字和newInstance()方法的区别

转载:http://www.kuqin.com/shuoit/20160719/352659.html 用最简单的描述来区分new关键字和newInstance()方法的区别:newInstance: 弱类型.低效率.只能调用无参构造.new: 强类型.相对高效.能调用任何public构造. newInstance( )是一个方法,而new是一个关键字,其次,Class下的newInstance()的使用有局限,因为它生成对象只能调用无参的构造函数,而使用new关键字生成对象没有这个限制.Cla

C语言实现strlen()4种方法和strcat()3种方法

#include <stdio.h> #include <assert.h> #if 0 // 默认使用法4 // 法1 int strlen(const char* str) { int n; // const char *p = str; //测试这句,这个语句不需要,因为我实参是指针,形参指针改变指向不影响实参指向 for(n = 0; *str != '\0'; n++) { str++; } return n; } #elif 0 // 法2 int strlen(con

Android中Path类的lineTo方法和quadTo方法画线的区别

当我们需要在屏幕上形成画线时,Path类的应用是必不可少的,而Path类的lineTo和quadTo方法实现的绘制线路形式也是不一样的,下面就以代码的实现来直观的探究这两个方法的功能实现区别: 1. Path--->quadTo(float x1, float y1, float x2, float y2): 该方法的实现是当我们不仅仅是画一条线甚至是画弧线时会形成平滑的曲线,该曲线又称为"贝塞尔曲线"(Bezier curve),其中,x1,y1为控制点的坐标值,x2,y2为终

angular中自定义依赖注入的方法和decorator修饰

自定义依赖注入的方法 1.factory('name',function () { return function(){ } }); 2.provider('name',function(){ this.$get=function(){ return function(){ } }; }); 3.service('name',function(){ this.n=v; }); 4.constant('name','value'); 5value('name','value'); 依赖的继承  

详解Integer.toString(int i)方法和String.valueOf(int i)方法

通过查看String类的源码: public static String valueOf(int i) { return Integer.toString(i); } 我们可以看到,String.valueOf(int i)其实是调用了Integer.toString(int i)方法的. 再次通过查看Integer类的源码我们可以看到: public static String toString(int i) { if (i == Integer.MIN_VALUE) return "-214