2014-09-02 54 views
0

當我在onCreate方法之外聲明TextView時,我的應用程序停止,我這樣做是因爲我需要從其他方法訪問TextView變量。我會很感激任何幫助。在onCreate之外聲明變量 - Android

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"); 
    } 
} 
+0

只需將TextView定義爲一個類作用域變量(即將它放在任何方法範圍外的類的頂部) – Booger 2014-09-02 22:02:22

+0

在Logcat中查找實際的錯誤消息當您提出這樣的問題時,請將Logcat – 2014-09-02 22:05:04

+0

@Dale在閱讀代碼時答案很清楚 – TehCoder 2014-09-02 22:06:12

回答

2
My application stops when I declare the TextView outside the onCreate method 

這是因爲佈局尚未膨脹您的活動因此崩潰您的應用程序,我100%肯定誤差NPE如果您在此處設置文本:textView.setText("Hello");

解決方案:

總是初始化你TextViewOncreatesetContentView後讓您的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(...)

0

正如有人指出,你所得到的錯誤是因爲尚未充氣含有的TextView作爲一個孩子的看法。您應該聲明強引用,然後在onCreate()方法上實例化變量。如果你堅持使用這樣的代碼,那麼我建議你看看依賴注入。

0

爲此:

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

如果不行不通,您首先將內容視圖設置爲活動。