我不能使用声明的TextView

时间:2013-07-21 00:54:55

标签: android android-fragmentactivity

public class DemoActivity extends FragmentActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_demo);
}
TextView textView = (TextView) findViewById(R.id.demo1);
textview.setText("hi"); 

它不会识别textView,那么我无法使用它的方法,所以我无法继续。可能会发生什么?

布局是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView 
    android:id="@+id/demo1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

 </LinearLayout>

1 个答案:

答案 0 :(得分:2)

它不在onCreate()中,因此无法识别,将其放入onCreate()

public class DemoActivity extends FragmentActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_demo);
    TextView textView = (TextView) findViewById(R.id.demo1);
    textview.setText("hi"); 

}