Android上下文菜单不出现

问题描述:

我的问题就像它在说明中所述,上下文菜单没有出现在用户的“触摸并按住”上。我有一种感觉,它可能是我放置的地方registerForContextMenu
这里是我的MainActivity:Android上下文菜单不出现

import java.util.ArrayList; 
import android.app.ListActivity; 
import android.media.MediaPlayer; 
import android.os.Bundle; 
import android.view.ContextMenu; 
import android.view.ContextMenu.ContextMenuInfo; 
import android.view.MenuInflater; 
import android.view.View; 
import android.widget.ListView; 
public class MainActivity extends ListActivity { 
private ArrayList<Sound> mSounds = null; 
private SoundAdapter mAdapter = null; 
static MediaPlayer mMediaPlayer = null; 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
registerForContextMenu(getListView()); 
setContentView(R.layout.activity_main); 
this.getListView().setSelector(R.drawable.selector); 
//create a simple list 
mSounds = new ArrayList<Sound>(); 
Sound s = new Sound(); 
s.setDescription("Anjels"); 
s.setSoundResourceId(R.raw.anjels); 
mSounds.add(s); 
s = new Sound(); 
s.setDescription("Aggro"); 
s.setSoundResourceId(R.raw.aggro); 
mSounds.add(s); 
s = new Sound(); 
s.setDescription("Basix"); 
s.setSoundResourceId(R.raw.basix); 
mSounds.add(s); 
s = new Sound(); 
s.setDescription("Bender"); 
s.setSoundResourceId(R.raw.bender); 
mSounds.add(s); 
mAdapter = new SoundAdapter(this, R.layout.list_row, mSounds); 
setListAdapter(mAdapter); 
} 
@Override 
public void onListItemClick(ListView parent, View v, int position, long id){ 
Sound s = (Sound) mSounds.get(position); 
MediaPlayer mp = MediaPlayer.create(this, s.getSoundResourceId()); 
mp.start(); 

} 
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 
    super.onCreateContextMenu(menu, v, menuInfo); 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.context_menu, menu); 
    } 
} 
+0

您使用的是哪个版本的Android? – MiStr

+0

实际设备的目标?目标是api“10”ICS,但我在api“16”上运行SGS3mini Jellybean –

尝试这两条线周围

registerForContextMenu(getListView()); 
setContentView(R.layout.activity_main); 

切换所以它应该是

setContentView(R.layout.activity_main); 
registerForContextMenu(getListView()); 

你的感觉是正确的。您的ListView在您的layout中,因此您需要先注册View

+0

我可以问一下,所以我可以从中学习,为什么这种差异首先出现这种差异? –

+0

正如我在答案的最后一句中所说的那样,你的“视图”存在于你的“布局”中,因此它就像在根布局已经膨胀之前一样不存在。同样的原因,如果你在调用'setContentView()之前尝试初始化一个'View',它将返回'null',并且你不能使用它的方法或者监听器 – codeMagic

+0

我希望这很有道理 – codeMagic

我认为“触摸并保持”从用户的意思是“长按”?

如果是这样,请尝试查看this post以查看您的问题是否相似。也许你需要使用setOnLongClickListener ...

+0

感谢您的答复,经过一天的头部划伤,我终于发现了什么是错的。 –