2013-04-16 22 views
0

我正在使用列表視圖。我使用適配器爲這個列表添加項目。我正在嘗試爲列表中的每個項目添加contextmenu,但我對此有問題。用於列表視圖的contextMenu

這裏是我的代碼

項目列表:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="@color/bgActivity" 
android:orientation="horizontal" > 

<TextView 
    android:id="@+id/tv_name" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:paddingLeft="10dp" 
    android:textColor="@color/textColorContact" 
    android:textSize="20sp" 
    android:textStyle="bold" /> 

<Button 
    android:id="@+id/pick_options" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:layout_marginRight="10dp" 
    android:background="@drawable/app_icon" 
    android:text="@string/label_options" > 
</Button> 

</RelativeLayout> 

名單:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<ListView 
    android:id="@+id/lst_contacts" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@color/bgContactItem" /> 

</RelativeLayout> 

菜單:

<menu 
xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:id="@+id/CtxLblOpc1" android:title="OpcEtiqueta1"></item> 
<item android:id="@+id/CtxLblOpc2" android:title="OpcEtiqueta2"></item> 
</menu> 

java代碼:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_contacts); 

// Getting reference to listview 
    ListView lstContacts = (ListView) findViewById(R.id.lst_contacts); 
registerForContextMenu(lstContacts); 
} 

@Override 
    public void onCreateContextMenu(ContextMenu menu, 
            View v, 
            ContextMenuInfo menuInfo) { 
    super.onCreateContextMenu(menu, v, menuInfo); 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.menu_options, menu); 


} 


/** Actions for the ContextMenu items */ 
@Override 
public boolean onContextItemSelected(MenuItem item) { 
    //AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
    switch (item.getItemId()) { 
     case R.id.CtxLblOpc1: 
     Toast.makeText(getApplicationContext(), 
         "Option 1",  
         Toast.LENGTH_LONG).show(); 
      return true; 
     case R.id.CtxLblOpc2: 
     Toast.makeText(getApplicationContext(), 
         "Option 2", 
         Toast.LENGTH_LONG).show(); 
      return true; 
     default: 
      return super.onContextItemSelected(item); 
    } 
} 

,但我沒有看到文本菜單,請幫忙,謝謝

回答

0

我想你應該嘗試添加(佈局)

android:descendantFocusability="blocksDescendants" 

在佈局中。 你可以看看here 我建議你使用ActionMode.Callback的上下文菜單。如果你想要一個例子來看一下here

注:鏈接是從我的博客