在自定义ListView中单击Long时创建上下文菜单

时间:2014-01-22 12:58:25

标签: java android listview android-listview

我想在使用自定义列表适配器创建的自定义列表中显示带有删除和编辑选项的上下文菜单(OnClickLong)。我将发布代码

SpotListFragment

package com.pap.myspots.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.pap.myspots.R;
import com.pap.myspots.R.layout;
import com.pap.myspots.database.DBAdapter;
import com.pap.myspots.listView.SpotList;
import com.pap.myspots.listView.SpotListAdapter;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class SpotListFragment extends Fragment implements OnClickListener{

    String nome;
    String local;
    Button createToast;
    List<String> nomes ;
    List<String> locais ;
    ListView listView;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_spotlist, container, false);

        DBAdapter db = new DBAdapter(getActivity());
        db.open();
        Cursor cursor = db.getAllTitles();
        nomes = new ArrayList<String>();
        while(cursor.moveToNext()){
            String uname = cursor.getString(cursor.getColumnIndex("nome"));
            nomes.add(uname);
        }

        Cursor cursor2 = db.getAllTitles();
        locais = new ArrayList<String>();
        while(cursor2.moveToNext()){
            String ulocal = cursor2.getString(cursor.getColumnIndex("local"));
            locais.add(ulocal);
        }

       SpotListAdapter adapter = new SpotListAdapter(getActivity(), generateData());

       // 2. Get ListView from activity_main.xml
       listView = (ListView) rootView.findViewById(R.id.spotList);

       // 3. setListAdapter
       listView.setAdapter(adapter);

        return rootView;

        }

    private ArrayList<SpotList> generateData(){
        ArrayList<SpotList> items = new ArrayList<SpotList>();
        int i = 0;
        while(nomes.size()>i){
            items.add(new SpotList(new String(nomes.get(i)),new String(locais.get(i))));
            i++;
        }
        return items;
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

    //Deleted individual cart items



}

SpotListAdapter

package com.pap.myspots.listView;

import java.util.ArrayList;

import com.pap.myspots.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SpotListAdapter extends ArrayAdapter<SpotList> {
     private final Context context;
     private final ArrayList<SpotList> itemsArrayList;

     public SpotListAdapter(Context context, ArrayList<SpotList> itemsArrayList) {

         super(context, R.layout.list_row, itemsArrayList);

         this.context = context;
         this.itemsArrayList = itemsArrayList;
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {

         // 1. Create inflater 
         LayoutInflater inflater = (LayoutInflater) context
             .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

         // 2. Get rowView from inflater
         View rowView = inflater.inflate(R.layout.list_row, parent, false);

         // 3. Get the two text view from the rowView
         TextView labelView = (TextView) rowView.findViewById(R.id.title);
         TextView valueView = (TextView) rowView.findViewById(R.id.place);

         // 4. Set the text for textView 
         labelView.setText(itemsArrayList.get(position).getNome());
         valueView.setText(itemsArrayList.get(position).getLocal());

         // 5. retrn rowView
         return rowView;
     }
}

SpotList(豆类)

package com.pap.myspots.listView;

public class SpotList {

    public SpotList(String nome, String local) {
        super();
        this.nome = nome;
        this.local = local;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getLocal() {
        return local;
    }

    public void setLocal(String local) {
        this.local = local;
    }

    private String nome;
    private String local;


}

5 个答案:

答案 0 :(得分:6)

首先在onCreate方法中注册listView以获取上下文菜单:

registerForContextMenu(yourListView);

通过覆盖onCreateContextMenu:

来创建contextmenu
@Override 
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
    _listPosition = info.position;      // Get Index of long-clicked item

    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Choose Action");   // Context-menu title
    menu.add(0, v.getId(), 0, "Edit");  // Add element "Edit"
    menu.add(0, v.getId(), 1, "Delete");        // Add element "Delete"
}

对上下文菜单中的点击进行反应:

 @Override  
 public boolean onContextItemSelected(MenuItem item)
 {
      if(item.getTitle() == "Edit") // "Edit" chosen
      {
         // Do stuff
      }
      else if(item.getTitle() == "Delete")  // "Delete" chosen
      {
          // Do stuff
      }
      else 
      {
         return false;
      }

      return true;  
 }  

答案 1 :(得分:1)

下次只需花几分钟时间自行google:

覆盖 onCreateContextMenu()以创建菜单, onContextItemSelected()来处理点击事件

您还需要为上下文菜单注册listView。您可以在片段的 onActivityCreated()方法中执行此操作:

registerForContextMenu(listView);

答案 2 :(得分:0)

您必须使用上下文菜单注册自定义ListView。使用方法registerForContextMenu(listView);。在onCreate

中调用此方法

答案 3 :(得分:0)

我会在您的覆盖onLongClickListener扩展程序的getView()方法中定义ArrayList。只需使用registerForContextView(convertView)在长按一下监听器中注册视图。

现在,在您的活动代码中,只需像在任何其他情况下一样定义上下文菜单:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
  ...    
  menu.setHeaderTitle(...);
  menu.add(...);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
  final int mId = item.getItemId();

  switch (mId) {
    case 0: 
    ...
    break;

  default:
    break;
}

答案 4 :(得分:0)

更精确:

 @Override  
        public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
        super.onCreateContextMenu(menu, v, menuInfo);  
        TreeViewList v1=(TreeViewList) v; //my custom listview
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        final LinearLayout viewLayout = (LinearLayout) v1.getChildAt(info.position-v1.getFirstVisiblePosition());//if in list many items
        final TextView descriptionView = (TextView) viewLayout
                .findViewById(R.id.list_item_description);
            menu.add(0, v.getId(), 0, descriptionView.getText());  
            menu.add(0, v.getId(), 0, "Action 2");  
        }