【发布时间】:2016-01-27 13:08:48
【问题描述】:
我在网格视图中使用 launcherIcons 类传递图像和文本。正如下面的代码,工作正常。 但我想将字符串更改为
new LauncherIcon(R.mipmap.ic_launcher,getResources().getString(R.string.hello))
我想从 Resources(R.string.hello) 中获取字符串,当实现 getResources 警告 "Non-static Method getResources cannot be referenced from a static-context"
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
String Activity="MainActivity";
Context activity_context=MainActivity.this;
static final LauncherIcon[] ICONS = {
new LauncherIcon(R.mipmap.ic_launcher,"Hello"),
new LauncherIcon(R.mipmap.ic_launcher, "About me"),
new LauncherIcon(R.mipmap.ic_launcher, "Venky"),
new LauncherIcon(R.mipmap.ic_launcher, "Noctilien"),
new LauncherIcon(R.mipmap.ic_launcher, "Metro"),
new LauncherIcon(R.mipmap.ic_launcher, "RER"),
new LauncherIcon(R.mipmap.ic_launcher, "Bus"),
new LauncherIcon(R.mipmap.ic_launcher, "Metro"),
new LauncherIcon(R.mipmap.ic_launcher, "RER"),
new LauncherIcon(R.mipmap.ic_launcher, "Bus"),
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//blah blah.............
}
LauncherIcon 类
static class LauncherIcon {
final String text;
final int imgId;
//final String map;
public LauncherIcon(int imgId, String text) {
super();
this.imgId = imgId;
this.text = text;
// this.map = map;
}
}
如何在其中使用getResources String? 提前致谢。
【问题讨论】:
-
如果有人对我的问题投反对票。请澄清你为什么投反对票?
-
你为什么将你的数组声明为静态的?静态类需要什么?
-
你试过上下文吗? activity_context.getResources().getString(R.string.hello)
-
@Chol 不需要。 @ Venkatesh Sekvam 一旦创建活动,上下文也可用。所以在onCreate中移动context的初始化。从数组中删除静态。启动器图标看起来像模型类可以是一个单独的类,以防您将其作为活动的内部类
-
错误信息不够清楚?您不能从静态块调用非静态方法...
标签: java android android-resources static-members