0

我的第一个 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"/>
4

3 回答 3

2

我创建了一个 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" />

现在整行响应用户点击。

于 2012-07-06T21:06:54.510 回答
2

如果这对任何人都有帮助,另一种可能的解决方案是:我的每个列表项中都有一个 Button,这阻止了我的 onListItemClick 事件触发。用看起来完全相同的 TextView 替换 Button 使其工作。

于 2013-05-12T12:34:10.043 回答
0

实现 OnItemClickListener 并执行 list.setOnItemClickListener。

public class Notepadv1 extends ListActivity implements OnItemClickListener { 

   onCreate() 
   {
        ....

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

    }

}
于 2012-07-06T20:46:27.123 回答