当我使用上下文菜单检测到长按时,我试图从listfragment中获取单个项目。事物是它得到的项目是列表中的第一项而不是选中的项目,意思是......
如果我的列表看起来像这样
item 5
item 4
item 3
item 2
item 1
我长期坚持说item 2
它会给我item 5
@Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(Menu.NONE,Menu.NONE,Menu.NONE,"Delete");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
Vibrator vibrator = (Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(new long [] {0,20,0,0}, -1);
TextView tv = (TextView)getActivity().findViewById(R.id.bListTextView);
name = tv.getText().toString();
Log.d("List", name);
Cursor cID = getActivity().getContentResolver().query(BowlersDB.CONTENT_URI,new String[] {BowlersDB.ID,BowlersDB.NAME},BowlersDB.NAME + "=" + name,null,null);
String nameID = cID.getString(1);
getActivity().getContentResolver().delete(BowlersDB.CONTENT_URI,"_id" + "=" + nameID,null);
return super.onContextItemSelected(item);
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/bListTextView"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Large Text"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dp" />
</RelativeLayout>
在列表视图中,我通常只能通过ID获取textview,如此
mContactList = (ListView) findViewById(R.id.contactList);
mContactList.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0,View arg1,int arg2,long arg3) {
Vibrator v = (Vibrator)getSystemService(VIBRATOR_SERVICE);
v.vibrate(new long [] {0,20,0,0}, -1);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(Contacts.this);
SharedPreferences.Editor edit = pref.edit();
TextView tv =(TextView)arg1.findViewById(R.id.contactEntryText);
n = tv.getText().toString();
edit.putString(SmsPrefs.NAME, n).commit();
showDialog(1);
return false;
}
});
但这种方法似乎不起作用
答案 0 :(得分:2)
在onContextItemSelected中,您首先需要获取所选项目:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
然后您可以决定是通过ID还是位置查询,您可以从AdapterContextMenuInfo获取两者。
你这样做的方式(使用findViewById)我想它只会获取它在视图层次结构中可以找到的第一个视图,即列表中的第一个视图。