Search code examples
androidandroid-fragmentactivity

I can't use declared TextView


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"); 

It won't recognize textView, then I can't use its methods so I can't continue. What can possibly be happening?

layout is:

<?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>

Solution

  • it is out of onCreate() thus it can't recognize, put it in 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"); 
    
    }