1

我有以下動作。Android無法從活動中訪問textView組件

package org.dewsworld.ui; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 

public class DetailList extends Activity { 

    TextView title = (TextView) findViewById(R.id.title) ; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.detail_list); 

     title.setText("hello world"); 
    } 

} 

哪個操縱detail_list.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" android:weightSum="1"> 
    <TextView android:id="@+id/title" android:textAppearance="?android:attr/textAppearanceMedium" 
     android:layout_height="wrap_content" android:layout_width="match_parent" 
     android:text="@string/headline" /> 
    <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent"></ListView> 

</LinearLayout> 

但是,當我運行它,我得到一個運行時錯誤。 logcat的是,

enter image description here

回答

3

請試試這個

public class DetailList extends Activity { 
TextView title; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.detail_list); 

    title = (TextView) findViewById(R.id.title) ; 
    title.setText("hello world"); 
    } 
} 
2
package org.dewsworld.ui; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 

public class DetailList extends Activity { 

    TextView title; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.detail_list); 
     title = (TextView) findViewById(R.id.title) ;; 
     title.setText("hello world"); 
    } 

} 

的抱怨,因爲您嘗試使用它尚未創建的活動方法來獲得的TextView的值(由於其在OnCreate()尚未運行)

+0

是的。有用! :)謝謝你們兩位...... – Dewsworld