[英]Android: onListItemClick not getting called in ListActivity
我的第一个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"/>
我创建了一个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" />
现在,整个行都响应用户单击。
万一这对任何人都有用的话,另一个可能的解决方案是:我在每个列表项中都有一个Button,这阻止了onListItemClick事件的触发。 用看起来完全相同的TextView替换Button,使其可以工作。
实现OnItemClickListener并执行list.setOnItemClickListener。
public class Notepadv1 extends ListActivity implements OnItemClickListener {
onCreate()
{
....
((ListView)findViewById(android.R.id.list)).setOnItemClickListener(this)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.