如何从所选的Listview
项目中设置上下文菜单的标题?以下是主要活动。
public class OListActivity extends ListActivity {
......
......
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerForContextMenu(getListView());
......
......
MatrixCursor cursor;
cursor = NameManager.getnameList();
startManagingCursor(cursor);
String[] from = { "name", "info", "status", BaseColumns._ID };
int[] to = { R.id.name, R.id.info, R.id.status };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.row, cursor, from, to);
setListAdapter(adapter);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Menu");// TODO Change to name of selected listview item.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
.....
.....
我需要将menu.setHeaderTitle
设置为R.id.name
。我知道另一个similer question,但它没有提到处理具有多个textview的复杂ListView
。
答案 0 :(得分:14)
使用ContextMenuInfo
方法中的onCreateContextMenu()
参数:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info;
try {
// Casts the incoming data object into the type for AdapterView objects.
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
// If the menu object can't be cast, logs an error.
Log.e(TAG, "bad menuInfo", e);
return;
}
Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
if (cursor == null) {
// For some reason the requested item isn't available, do nothing
return;
}
// if your column name is "name"
menu.setHeaderTitle(cursor.getString(cursor.getColumnIndex("name")));
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
答案 1 :(得分:0)
我知道这是一个很老的帖子,也是正确的答案。然而,今天使用这个时我遇到了一些我想补充的内容。
ContextMenuInfo
参数用于查找启动ContextMenu的确切项目位置,即我们的adpater项目。
因此,它可以使用该位置getItem()
返回Adapter的info.position
方法中定义的类型的项,如上所述,getItem()方法返回 Cursor 对象。
(在我的情况下,它返回了一个Model类,然后我意识到要通过menu.setHeaderTitle()
设置标题我可以传递我的模型支持的方法,如model.getItamName()
)
另外,请记住,如果您的AdapterView包含任何标题,则在使用menuInfo获取位置时必须将其排除。像,
Cursor cursor = (Cursor) getListAdapter().getItem(info.position - yourList.getHeaderViewsCount());
希望这有助于某人。 :)