Bruno Lorenço
Bruno Lorenço

Reputation: 35

Create a Context Menu when Click Long in a Custom ListView

I want to show a context menu (OnClickLong)with delete and edit option, in a custom list i created with a custom list adapter. i will post the code

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(Beans)

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;


}

Upvotes: 1

Views: 4129

Answers (5)

Master
Master

Reputation: 683

More precision:

 @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");  
        } 

Upvotes: 0

user3218281
user3218281

Reputation: 133

So first of all register your listView for a context menu in the onCreate method:

registerForContextMenu(yourListView);

Create the contextmenu by overridig the onCreateContextMenu:

@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"
}

React on clicks in context-menu:

 @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;  
 }  

Upvotes: 6

Marqs
Marqs

Reputation: 17910

Next time just spend few minutes and google it yourself:

Override onCreateContextMenu() to create the menu and onContextItemSelected() to handle the click event

You also need to register listView for the contextual menu. You can do it in fragment's onActivityCreated() method:

registerForContextMenu(listView);

Upvotes: 1

nKn
nKn

Reputation: 13761

I would define the onLongClickListener in the getView() method of your overriden ArrayList extension. Just register the view inside the long click listener, using registerForContextView(convertView).

Now in your Activity code, simply define the context menu as you would in any other case:

@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;
}

Upvotes: 0

Lalit Chattar
Lalit Chattar

Reputation: 1984

You have to register your custom ListView with Context Menu. Use Method registerForContextMenu(listView); . Call this method in onCreate

Upvotes: 0

Related Questions