【问题标题】:Declaring variables outside onCreate - Android在 onCreate 之外声明变量 - Android
【发布时间】:2014-10-27 06:57:40
【问题描述】:

当我在 onCreate 方法之外声明 TextView 时,我的应用程序停止,我这样做是因为我还需要从其他方法访问 TextView 变量。我将不胜感激。

public class MainActivity extends ActionBarActivity {
    TextView textView = (TextView)findViewById(R.id.defaultText);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        textView.setText("Hello");
    }
} 

【问题讨论】:

  • 只需将您的 TextView 定义为类作用域变量(即,将其放置在任何方法作用域之外的类的顶部。
  • 在 Logcat 中查找实际的错误消息。当您提出这样的问题时,请在您的问题中包含 Logcat 信息。
  • @Dale 阅读代码时答案很清楚。
  • @TehCoder 是的,但如果 OP 看过 Logcat,他就不需要问这个问题,而且这个问题不太可能帮助未来的 SO 用户。

标签: java android


【解决方案1】:
My application stops when I declare the TextView outside the onCreate method

那是因为布局尚未在您的活动中膨胀,从而导致您的应用程序崩溃,我 100% 确定当您在此处设置文本时错误是 NPEtextView.setText("Hello");

解决方案:

始终在setContentView 之后在Oncreate 中初始化您的TextView,并将您的textView 对象作为全局实例。

public class MainActivity extends ActionBarActivity {
   TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.defaultText);
        textView.setText("Hello");
    }
}

【讨论】:

    【解决方案2】:

    你不能在函数之外声明视图。

    TextView tv; 并在 OnCreate 做: tv = (TextView)findViewById(...)

    【讨论】:

      【解决方案3】:

      正如其他人指出的那样,您得到的错误是因为包含 TextView 作为子项的视图尚未膨胀。您应该声明强引用,然后在 onCreate() 方法上实例化变量。如果你坚持使用这样的代码,那么我建议你看看依赖注入。

      【讨论】:

        【解决方案4】:

        为此:

        TextView textView = (TextView)findViewById(R.id.defaultText);
        

        您首先将内容视图设置为Activity,否则将不起作用。

        【讨论】:

          【解决方案5】:

          我遇到了这个问题,我通过使用 (tag) 作为我的视图来解决它 (myTextView.tag) 你可以从这里更多地了解这个属性:

          What is the main purpose of setTag() getTag() methods of View?

          我的意思是我在 onCreate 方法之外声明了一个名为 (counter) 的变量,然后我可以使用他的标签在任何需要的地方找到我的视图。

          希望对你有所帮助

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-09-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-11-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多