2011-07-05 37 views
0

我是新來的android,雖然我之前在一個簡單的項目上得到了這個工作,但我不能爲我的生活弄清楚發生了什麼。ListView setOnItemClickListener沒有執行

這裏是我的ListActivity類的代碼:我能夠獲得列表中顯示我想要的內容

public class ResultsActivity extends ListActivity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 

     // Get rid of the default title bar 
     this.requestWindowFeature(Window.FEATURE_NO_TITLE); 

     Bundle extras = this.getIntent().getExtras(); 
     if (extras != null) 
     { 
      String[] results = extras.getStringArray("results_to_display"); 
      this.setListAdapter(new ArrayAdapter<String>(this, R.layout.result_list_item, results)); 

      ListView listView = this.getListView(); 
      listView.setTextFilterEnabled(true); 
      Toast.makeText(getApplicationContext(), "hello there", Toast.LENGTH_LONG).show(); 

      listView.setOnItemClickListener(new OnItemClickListener() { 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
       { 
        Log.d(ACTIVITY_SERVICE, "here now"); 
        Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     } 

     this.setContentView(R.layout.result_list); 
    } 
} 

,但是,它看起來像onItemClick沒有得到執行的項目,當點擊。我也在那裏放了一個斷點。

這是我的佈局文件(不知道這是否有差別)

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/contentContainer" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#FFFFFF"> 
    <ListView 
     android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1"/> 
</LinearLayout> 

任何幫助,將不勝感激!

回答

3

在ListActivity您可以覆蓋onListItemClick:

public class ResultsActivity extends ListActivity { 
    protected void onListItemClick (ListView l, View v, int position, long id){ 

    } 
} 

編輯

我發現這個問題。您可以在onCreate的結尾處設置佈局(使用setContentView)。您正在設置OnItemClickListener的ListView不是您正在看到的ListView。

如果您自己沒有設置ListActivity,則ListActivity會創建自己的contentView。因此,您將OnClickListener添加到「默認」ListView中,並在onCreate的結尾處將默認的一個替換爲新的,因爲調用了setContentView。

實際上,人們可以在不設置contentView的情況下創建ListActivity。

要解決該問題,請將onCreate頂部的setContentView移動。

+0

謝謝。這確實解決了這個問題,但我想知道他們爲什麼在Android網站的教程中不工作(http://developer.android.com/resources/tutorials/views/hello-listview.html)使用ListActivity。 – PolandSpring

+0

嗯,我在幾個月前遇到過同樣的問題。我不知道。也許這個例子太舊了? – thaussma

+0

我找到了原因並編輯了答案。 – thaussma

相關問題