如何从ListFragment获取信息

时间:2012-11-16 22:21:26

标签: android android-listfragment android-cursorloader

我有一个使用CursorLoader填充的ListFragment。填充ListFragment后,我有一个OnItemClickListener方法,我想在其中识别用户选择的List Fragment中的哪个项目。我该怎么做呢?我试过了:

String item = getListAdapter().getItem(position);
String item = getListAdapter().getItem(position).toString();

String item = (String) ((Fragment) getListAdapter().getItem(position)).getString(0);

其中position是传递给onClickItemListener方法的整数,如下所示:

public void onListItemClick(ListView l, View v, int position, long id)

所有这些都会抛出一种或另一种类型的强制转换异常。我很难过。这似乎是一件简单的事情。供您参考,以下是填充List Fragment的方法:

private SimpleCursorAdapter mAdapter;
private static final String[] PROJECTION = new String[] { "_id", "stitchname" };
@Override
public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);
  Intent myData = getActivity().getIntent();
  Bundle info = myData.getExtras();
  String[] dataColumns = { "stitchname" };
  int[] viewIDs = { R.id.stitchlist1 };
  mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.stitchlist, null, dataColumns, viewIDs, 0);
  setListAdapter(mAdapter);
  getLoaderManager().initLoader(0, info, (LoaderCallbacks<Cursor>) this); 
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
  String selection = "stitchlevel=?";
  String[] selectionArgs = new String[] {args.getString("Level")};
  return (Loader<Cursor>) new CursorLoader(getActivity(), STITCHES_URI,                PROJECTION, selection, selectionArgs, null);  
 }

非常欢迎任何建议,谢谢!

2 个答案:

答案 0 :(得分:1)

你压倒了错误的方法。你说你正在使用ListFragment,所以你可能已经在片段中的某处声明了CursorAdapter / ArrayAdapter。在这种情况下,请执行以下操作:

class yourFragemt extends ListFragment{

   //Member Variable
   private SimpleCursorAdapter mAdapter;

   ....

   @Override
   public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {

       Cursor c = (Cursor) mAdapter.getItem(pos);

       String value = c.getString(c
            .getColumnIndex(ColumnIndex));

    }
}

答案 1 :(得分:1)

答案如下:

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

    Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
    c.moveToPosition(position);
    String item = c.getString(1);
}

我从Georgy Gobozov在上面的评论中提供给我的第二个链接中得到了答案。