setText(getString(R.strings.whatever)或setText(R.strings.whatever)?

Ste*_*ual 6 android

两者都有效,显然如果你开始连接,你需要获取字符串以避免显示int.

问题:哪种"优雅"或"推荐"使用?

谢谢

Luk*_*uth 9

第二种方法更优雅,因为在内部,TextView(或者任何View类)将完成获取指定资源的String的工作.

让组件完成内部工作总是首选.此外,它更短,更易读.


关于我所谈到的内部:如果你看一下Androids的源代码,你可以看到setText(int)-method TextView 是这样实现的:

public final void setText(int resid) {
  setText(getContext().getResources().getText(resid));
}
Run Code Online (Sandbox Code Playgroud)

因此,它在内部使用Context-class从resource-id获取字符串.现在,如果您查看getText()-method(也来自Context-class),您可以看到它以相同的方式实现:

public final String getString(int resId) {
  return getResources().getString(resId);
}
Run Code Online (Sandbox Code Playgroud)

因此,出于性能或可靠性的原因,它没有任何区别.它仍然更短,更具可读性.