2012-10-27 74 views
0

我想在android中做一個listview,但我有一些麻煩。Android的ListView不起作用

這是代碼:

public class MainActivity extends Activity 
{ 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     String[] items = {"red", "blue", "green"}; 

     ListView listView = (ListView) findViewById(R.id.list); 
     listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, items)); 
    } 
} 

而這個XML文件:

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

    <Button 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:text="Agregar Tarea" 
     android:id="@+id/btn" /> 

    <ListView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/list" /> 

</RelativeLayout> 

的logcat的說有在第21行NullPointerException異常,這條線:

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

但我不知道爲什麼:(

我想以這種方式做列表視圖,如果我使用listactivity頭/頁腳不固定。

回答

0

嘗試改變這種

android:layout_below="@+id/list" 

這樣:

android:id="@+id/list" 
+0

哦......我的錯誤呢!我fotgot把id XD。謝謝 – leojg

0

你的列表視圖ID不存在

android:id="@+id/list" 
android:layout_below="@+id/btn" 
1

在xml佈局中添加listview標識。

由於id空指針異常被拋出。

android:id="@+id/list" 

代替

android:layout_below="@+id/list" 

,改變上述行這樣

android:layout_below="@+id/btn"