2011-01-20 100 views
0

我通过ListAdapter在列表中显示一些sql数据。除非我尝试为列表中的每个项目设置单击侦听器,否则一切正常。当我点击任何项目时没有任何反应;没有错误信息,它只是默默地失败。android onItemClick默默失败

public class Notes extends ListActivity implements OnClickListener { 
    private static final String TAG = "Notes"; 
    private NotesData notes; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     notes = new NotesData(this); 
     try { 
      Cursor cursor = getNotes(); 
      showNotes(cursor); /* set the cursor to the listadapter */ 
      ListView ls = (ListView) findViewById(android.R.id.list); 
      ls.setOnItemClickListener(new OnItemClickListener() { 
       public void onItemClick(AdapterView<?> parent,View v, 
        int position,long id) { 
        Toast.makeText(getApplicationContext(),"clicked", 
         Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     } finally { 
      notes.close(); 
     } 

    } 

main.xml中,包含列表视图:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
<Button 
android:id="@+id/new_note_button" 
android:layout_height="wrap_content" 
android:layout_width="fill_parent" 
android:text="@string/new_note"/> 
<ListView 
android:id="@android:id/list" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" /> 
<TextView 
    android:id="@+id/empty" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:text="@string/empty"/> 
</LinearLayout> 

有我丢失的东西?

+0

还检查您的列表视图设置为启用,可点击和可调焦。 – 2011-01-20 02:26:13

+0

FYI`android:id =“@ + id/empty”`应该是`android:id =“@ android:id/empty”` – idbrii 2011-01-20 02:44:55

回答

0

没有什么缺失,你的代码是完全正确的,只需将getApplicationContext()替换为“this”就可以解决问题,因为你需要传递的是对当前组件的上下文的引用,而不是上下文目前的过程。

希望它有帮助。 哈斯。

0

我想你的列表项目是可点击的。 (view.setClickable(true))

onItemClick将在列表项可点击时调用。

-1

我建议你try语句

try{ 
    //yourstuff 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

抛出这样的事情再检查,看看是什么错误被抛出。当它设置onClickListener时可能会抛出错误,也许有些东西是无效的,但只要所有这些都在try语句中,它就不会给你任何有用的错误信息。所以你也可以尽可能多地从try语句中拉出来,直到你发现问题。 :-)

0

您需要将android:focusable="false"添加到main.xml文件中的按钮。该按钮将焦点远离列表项目。

这确实解决了您的问题。