2013-08-06 65 views
0

我的問題就像它在說明中所述,上下文菜單沒有出現在用戶的「觸摸並按住」上。我有一種感覺,它可能是我放置的地方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 –

回答

1

嘗試這兩條線周圍

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

0

我認爲「觸摸並保持」從用戶的意思是「長按」?

如果是這樣,請嘗試查看this post以查看您的問題是否相似。也許你需要使用setOnLongClickListener ...

+0

感謝您的答覆,經過一天的頭部劃傷,我終於發現了什麼是錯的。 –