我最近從ListView遷移到RecyclerView ... 除了我不知道如何從RecyclerView項目獲取數據,一切似乎都很好... 在ListView Item OnClick,我以前使用getItemAtPosition
,但它不存在於RecyclerView ...從RecyclerView的項目獲取的位置數據
這裏是代碼的相關部分... - MainActivity.java
private SDKP mSelectedPackage;
RecyclerView mRecyclerView;
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
//I'm STUCK HERE!
mSelectedPackage = (SDKPackage) mRecyclerView.getItemAtPosition(position);
openContextMenu(view);
/*Toast.makeText(MainActivity.this, "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();*/
}
}));
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
mSelectedPackage.inflateMenu(menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
return mSelectedPackage.onMenuClick(this, item);
}
這裏的inflateMenu(文本菜單菜單)方法 -
public void inflateMenu(ContextMenu menu)
{
menu.setHeaderTitle(getPackageName());
if (isDownloading())
{
menu.add(Menu.NONE, 256, Menu.NONE, "Cancel download");
}
else if (isInstalled())
{
menu.add(Menu.NONE, 257, Menu.NONE, "Uninstall");
}
else
{
int i = 0;
for (SDKA archive : archives)
{
menu.add(Menu.NONE, i++, Menu.NONE, archive.getArchiveName());
}
}
}
public boolean onMenuClick(Activity parent, MenuItem item)
{
if (item.getItemId() >= 256)
uninstall();
else
{
SDKA archive = archives.get(item.getItemId());
if (archive != null)
{
archive.onClick(parent);
}
}
return true;
}
當我使用的ListView我用 -
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg)
{
mSelectedPackage = (SDKP) mPackageList.getItemAtPosition(position);
openContextMenu(view);
}
});
使用'getAdapterPosition()' –