安卓:onListItemClick没有得到所谓的ListActivity(Android: onL

2019-09-19 04:29发布

我有我的第一个Android应用程序的问题。

我已经子类ListActivity,和我有没有运气得到覆盖onListItemClick()响应单击事件。 我读过的焦点可能是一个问题,但在XML文件中改变的重点似乎不工作。 下面是代码的相关位。 任何人都看到发生了什么,我鸡奸了?

public class Notepadv1 extends ListActivity {
    private int mNoteNumber = 1;
    private NotesDbAdapter mDbHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notepad_list);
        mDbHelper = new NotesDbAdapter(this);
        mDbHelper.open();
        fillData();
    }

 private void fillData() {
    // Get all of the notes from the database and create the item list
    Cursor c = mDbHelper.fetchAllNotes();
    startManagingCursor(c);

    String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
    int[] to = new int[] { R.id.text1 };


    SimpleCursorAdapter notes =
        new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
    setListAdapter(notes);
}

@Override
public void onListItemClick (ListView l, View v, int position, long id){
    super.onListItemClick(l, v, position, id);

    AlertDialog alert = new AlertDialog.Builder(this).create();
    String message = "row clicked!";
    alert.setMessage(message);
    alert.show();

}

notepad_list.xml

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

  <ListView
      android:id="@android:id/list"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:dividerHeight="6dp"/>



  <TextView android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/no_notes" />

</LinearLayout>

和notes_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:focusable="false"/>

Answer 1:

我创建了一个ListActivity,用你的onListItemClick和notes_row.xml。 该代码为我工作。 不过,我相信你期待整行的点击反应,根据notes_row您需要点击文本本身(在该行中没有在任何地方)。

尝试在notes_row.xml改变width属性"match_parent"

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    android:layout_height="60dp"
    android:layout_width="match_parent"
    android:focusable="false" />

现在整个行来响应用户点击。



Answer 2:

在另一种情况下,潜在的解决方案这可以帮助任何人:我曾在我的每个列表项的按钮,这阻止我onListItemClick事件烧制而成。 与跟以前一样使工作一个TextView更换按钮。



Answer 3:

实现OnItemClickListener做list.setOnItemClickListener。

public class Notepadv1 extends ListActivity implements OnItemClickListener { 

   onCreate() 
   {
        ....

       ((ListView)findViewById(android.R.id.list)).setOnItemClickListener(this)

    }

}


文章来源: Android: onListItemClick not getting called in ListActivity