Android的资源作为主要活动的成员变量 [英] Android resources as a member variable in the main activity

查看:227
本文介绍了Android的资源作为主要活动的成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

工作android的世界你好,我旁边添加了一些字符串到的strings.xml资源文件。然后,我想我的主要活动类的成员变量设置为字符串之一的值:

Working the android hello world, I next added some strings to the strings.xml resource file. I then tried setting a member variable of my main activity class to the value of one of the strings:

public class MyActivity extends Activity {
  /** Called when the activity is first created. */
  public String myString = getString(R.string.MY_STRING); // compiles, but crashes

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView tv = new TextView(this); 
    tv.setText(myString);
    setContentView(tv);
  }     
}

当它崩溃,我得到这个在logcat中:
无法实例活动ComponentInfo {} com.myclass:显示java.lang.NullPointerException

When it crashes, I get this in the logcat: Unable to instantiate activity ComponentInfo{com.myclass}: java.lang.NullPointerException

所以,我做错了,或者这是预期的行为?展望文件过来,
我没有看到什么使我认为,虽然目前正在建设的主要活动的资源将不可用。

So, am I doing it wrong, or is this expected behavior? Looking over the documentation, I don't see anything to lead me to think that the resources wouldn't be available while the main activity is being constructed.

http://developer.android.com/guide/topics/资源/访问-resources.html

不过,我pretty确信这在其他类的工作 - 只是不是主要的活动课

However, I am pretty sure this will work in other classes--just not the main activity class.

推荐答案

我不认为你可以调用的getString上的活动类,因为它可能没有被正确初始化呢。您可能需要拆分的声明(把它作为一个公共字符串),然后分配(移动,为的onCreate)。

I don't think you can call getString on the Activity class as it may not have been properly initialised yet. You may need to split the declaration (keep it as a public String) and then the assignment (move that to onCreate).

public class MyActivity extends Activity {
      /** Called when the activity is first created. */
      public String myString;

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myString = getString(R.string.MY_STRING); // compiles, but crashes
        TextView tv = new TextView(this); 
        tv.setText(myString);
        setContentView(tv);
      }     
    }

这篇关于Android的资源作为主要活动的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆