我正在尝试实现上下文菜单。我有一个首选项列表,我可以获取pref列表中每个项目的视图和ID,但是,对于我的生活,我无法得到我的上下文菜单。当我长按一个pref项目时,我可以Toast它的ID和视图。我应该把onCreateContextMenu和onContextItemSelected放在哪里让我的菜单出现?我注释掉了registerForContextMenu(view);因为我仍然可以在没有它的情况下烘烤视图和ID。任何帮助都会很棒!
public class MainActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
ListView listView = getListView();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
ListView listView = (ListView) parent;
ListAdapter listAdapter = listView.getAdapter();
Object obj = listAdapter.getItem(position);
if (obj != null && obj instanceof View.OnLongClickListener) {
View.OnLongClickListener longListener = (View.OnLongClickListener) obj;
return longListener.onLongClick(view);
} else {
Preference pref = (Preference) obj;
// prefs
makeToast("pref toast - " + id + view);
//registerForContextMenu(view);
//onCreateContextMenu(R.menu.context_menu, view, ContextMenu.ContextMenuInfo menuInfo);
}
return true;
}
});
}
public boolean onLongClick(View v) {
// long click
//registerForContextMenu(v);
return true;
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflateLayout = getMenuInflater();
inflateLayout.inflate(R.menu.context_menu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
makeToast("mmm 1 slice");
break;
case R.id.item2:
makeToast("mmm 2 slices");
break;
}
return super.onOptionsItemSelected(item);
}
public void makeToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:0)
当您在视图上调用registerForContextMenu()
时,不需要为该视图设置OnLongClickListener
。所以,你已经拥有了所有正确的代码,你只是得到了一些额外的东西。试试这个:
public class MainActivity extends PreferenceActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
ListView listView = getListView();
registerForContextMenu(listView);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflateLayout = getMenuInflater();
inflateLayout.inflate(R.menu.context_menu, menu);
}
public boolean onContextItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
makeToast("mmm 1 slice");
break;
case R.id.item2:
makeToast("mmm 2 slices");
break;
}
return super.onOptionsItemSelected(item);
}
public void makeToast(String message)
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}