如何在getView中获取getItemAtPosition?

时间:2015-07-01 11:44:39

标签: android cursor android-cursoradapter getview

我有ImageView来自db的listItems,每个列表项都有两个Buttons(添加friend / rejectFriend)。 我也在使用CursorAdapter,在我的适配器内部,我使用getView()方法来设置侦听器并捕获当前项Button的点击次数。

这里的问题是: 我需要从db获取当前项目的一些数据,当我点击项目Button时(例如添加朋友)。所以在getView()参数的帮助下,我可以获得ListView项的位置,但getView()如何正确调用光标和getItemAtPosition

这是来自适配器类的getView()方法:

@Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        View view =  super.getView(position, convertView, parent);
        Button mAcceptNewFriend = (Button) view.findViewById(R.id.btn_itemFriendsAddNew_accept);
            Button mRejectNewFriend = (Button)view.findViewById(R.id.btn_itemFriendsAddNew_reject);

            mRejectNewFriend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mActivity, "user #" + position + " was removed", Toast.LENGTH_SHORT).show();

                }
            });
            mAcceptNewFriend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int friendId = mCursor.getInt(FriendsFragment.F_FRIEND_ID);
                }
            });
        return view;
    }

2 个答案:

答案 0 :(得分:1)

第二种可能的解决方案:

使用以下解决方案:使用CoursorAdapter的构造函数添加游标,然后在cursor.moveToPosition(position)方法中使用getView()Get correct cursor in CustomCursor Adapater getView()

答案 1 :(得分:0)

当您的父视图是listView时,您可以尝试在列中添加ListView填充listItemClick的方法,并在其中添加光标,例如:

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

   Cursor mycursor = (Cursor) getListView().getItemAtPosition(position); //I'm not sure for the getListView() part and I think that it could be (Cursor)l.getItemAtPosition(position); Please try with both suggestions if the first doesn't work for you
   Toast.makeText(mActivity, "mycursor.getString(1) " + mycursor.getString(1) +"   ", Toast.LENGTH_SHORT).show();
}