2015-10-20 84 views
0

我正在使用'ListView'和'ArrayAdapter'。我創建了一個名爲listview_simple_layout.xml的新XML文件。Android Studio ArrayAdapter不起作用程序崩潰

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

    <TextView xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/textView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Large Text" 
     android:background="#ff0" 
     android:textColor="#f00" 
     android:textSize="30dp" 
     android:textStyle="bold|italic" 
     android:typeface="serif" /> 

</LinearLayout> 

內onCreate方法,當我通過這個XML文件ArrayAdapter的構造和運行程序,它崩潰。請幫我... 這裏是我的onCreate功能:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     Employee[] eList = new Employee[5]; 
     eList[0] = new Employee("Jagga", "Detroit Michigan", 1, 5000.0); 
     eList[1] = new Employee("Bagga", "Alexandria Virginia", 2, 15000.0); 
     eList[2] = new Employee("Haji", "San Diego California", 3, 25000.0); 
     eList[3] = new Employee("Saqa", "Lahore Pakistan", 4, 35000.0); 
     eList[4] = new Employee("Saqa", "Lahore Pakistan", 4, 35000.0); 


     ListView lv = (ListView) findViewById(R.id.listView); 

     ArrayAdapter<Employee> ad = new ArrayAdapter<Employee>(this,  R.layout.listview_simple_layout, eList); 
     lv.setAdapter(ad); 

    } 

但每當我發表意見lv.setAdapter(廣告),它工作正常,但沒有顯示輸出。

回答

0

(此問題是由我的教練解決。這是他說)

好吧,如我所料。如果您在崩潰的錯誤仔細一看,上面寫着:

java.lang.IllegalStateException:ArrayAdapter需要的資源ID是一個TextView

但如果你看看你的佈局文件,它裏面裹着一個TextView線性佈局。所以數組適配器默認預期有一個TextView,但它的佈局比這更復雜。如果刪除外線性佈局,只是保持一個單一的TextView在佈局文件,你應該確定(再次看到活動PDF並注意這一步正在做)

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/textView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Large Text" 
    android:background="#ff0" 
    android:textColor="#f00" 
    android:textSize="30dp" 
    android:textStyle="bold|italic" 
    android:typeface="serif" /> 

Ofcourse我們可以指定非常複雜的佈局,但現在陣列適配器只接受一個TextView。因此,對於更復雜的東西,我們將不得不手動覆蓋陣列適配器類。