两个很棒的解决方案是,如果您从片段扩展 ListFragment,知道mListView.setOnItemClickListener
在创建活动之前不会调用它,正如@dheeraj-bhaskar 暗示的那样。此解决方案确保在创建活动时设置它
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long rowId) {
// Do the onItemClick action
Log.d("ROWSELECT", "" + rowId);
}
});
}
在查看 ListFragment 的源代码时,我遇到了这个
public class ListFragment extends Fragment {
...........................................
................................................
final private AdapterView.OnItemClickListener mOnClickListener
= new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
onListItemClick((ListView)parent, v, position, id);
}
};
.................................................................
........................................................................
public void onListItemClick(ListView l, View v, int position, long id)
{
}
}
附加了一个onItemClickListener
对象,它调用onListItemClick()
了其他类似的解决方案,其工作方式完全相同,即覆盖onListItemClick()
@Override
public void onListItemClick(ListView l, View v, int position, long rowId) {
super.onListItemClick(l, v, position, id);
// Do the onItemClick action
Log.d("ROWSELECT", "" + rowId);
}