2012-01-14 17 views
0

我想在我的主要活動中包括一個ListView。我的主要活動的java代碼如下所示: 公共類StylbugActivity extends Activity活動第一次創建時調用。 */如何實現ListView與活動的其餘部分

private ListView x; 
public void onCreate(Bundle savedinstanceState) { 
    super.onCreate(savedinstanceState); 
    String[] values = new String[] { "Android", "iPhone", "WindowsMobile", 
      "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", 
      "Linux", "OS/2" }; 
    x = (ListView) findViewById(R.id.list_list_view); 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, values); 
    x.setAdapter(adapter); 
} 

,而我的main.xml如下所示:

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

<TextView 
    android:id="@+id/wow" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:clickable="true" 
    android:onClick="what" 
    android:text="@string/hello" /> 

<Button 
    android:id="@+id/testButton" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:onClick="test1" 
    android:text="Button" /> 

<ListView 
    android:id="@+id/list_list_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 



</LinearLayout> 

但是當我測試我的程序了,它只是打破了我,當我嘗試啓動它。誰能幫忙?

+0

我做了一些測試,結果是因爲空指針異常而崩潰,因爲「x」原來是NULL – 2012-01-14 09:55:19

+1

此外,我意識到我沒有把setContentView(R.layout.main),當我作爲onCreate的第二行放入,x仍然返回NULL – 2012-01-14 10:14:29

+1

請用'setContentView'和錯誤原因更新您的文章。 – Jin35 2012-01-14 12:57:20

回答

0

如果您擴展ListActivity而不是活動它將正常工作。因爲你正在使用setContentView(R.layout.main),所以ListView x永遠不會被初始化。我不知道你想要完成什麼,但這會讓你的ListView工作。

public class ListExample extends ListActivity{ 
public void onCreate(Bundle savedinstanceState) { 
    super.onCreate(savedinstanceState); 
    String[] values = new String[] { "Android", "iPhone", "WindowsMobile", 
      "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", 
      "Linux", "OS/2" }; 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, values); 
    setListAdapter(adapter); 
} 
} 

你將不得不做一些其他的工作,使你的XML的TextView和Button在這個設置中工作。

您也可以使用您正在使用的路線,但必須設置ContentView(R.layout.main),否則您將繼續獲得NPE。

相關問題