最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【未解决】android中通过字符串的ID得到字符串本身且支持static方法

Android crifan 2929浏览 0评论

【背景】

折腾:

【已解决】android返回之前的活动页面Activity

期间,想要弄一个将一个函数genHintStrFromStrId变成static的,但是却提示:

Cannot make a static reference to the non-static method getText(int) from the type Context

所以,想要去搞清楚:

如何从一个string的id,去获得字符串本身。

【解决过程】

1.搜:

android string id to string

参考:

Android: How do I get string from resources using its name? – Stack Overflow

但是结果对于:

String mystring = getResources().getString(R.string.mystring);

也还是提示:

Cannot make a static reference to the non-static method getResources() from the type ContextThemeWrapper

2.参考:

android – get a resource (a string) from its unique integer – Stack Overflow

去试试:

结果都还是无法弄成static:

Cannot make a static reference to the non-static method getText()

 

暂时只能放弃。

3.后来改为:

只是获得string的id:

 public static int getCurCommTypeStrId(){
  int curCommTypeId= 0;
  CommunicationType commType = AppConfig.getInstance().getCurrentCommunicationType();
  if (commType == CommunicationType.BLUETOOTH) {
   curCommTypeId = R.string.communication_type_bluetooth;
  }
  else if (commType == CommunicationType.USB) {
   curCommTypeId = R.string.communication_type_usb;
  }
 
  return curCommTypeId;
 }

然后别处调用者调用到的时候再去从string的id获得真正的字符串:

    String disconnectedHintStr = getText(R.string.hardware_is_disconnected).toString();
    String curCommTypeStr = getText(CommunicationFactory.getCurCommTypeStrId()).toString();
    Toast.makeText(this, String.format(disconnectedHintStr, curCommTypeStr), Toast.LENGTH_LONG).show();

【总结】

Android中的getText(),getString()等函数,是没法弄成static的。。。

转载请注明:在路上 » 【未解决】android中通过字符串的ID得到字符串本身且支持static方法

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.177 seconds, using 22.05MB memory