Search code examples
androidandroid-listviewcustom-adapterandroid-contextmenu

Context menu android on Listview item with CustomAdapter doesn't show


I'm quite new at Android developing and I was trying to put a a context menu on my Listview that uses a CursorAdapter, I followed this examples https://www.youtube.com/watch?v=Pq9YQl0nfEk Using contextmenu with listview in android but the menu doesn't appear and I don't no why, appearently everything's OK.

These is the code of my activity

public class ProductsView extends AppCompatActivity {


    private FloatingActionButton botonAnadir;
    private ListView lvProducts;
    SetOfProductList mylist;
    private ProductAdapter productAdapter;
    Cursor cursor;
    private ProductList productList;
    private Long idProductList;
    private DBManager dbManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            productList = bundle.getParcelable("productList");
            setTitle(getResources().getString(R.string.show_products) + " " + productList.getName());
        }
        setContentView(R.layout.products_view);
        initialize();
    }
    private void initialize(){
        botonAnadir = (FloatingActionButton)findViewById(R.id.button_add_product);
        lvProducts = (ListView)findViewById(R.id.listViewProducts);
        dbManager = new DBManager(getApplicationContext());
        loadProducts();
        registerForContextMenu(lvProducts);

        botonAnadir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                creaNuevaLista();
            }
        });

        lvProducts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Product aux = getProduct(position);
                goToNewProduct(aux);
            }
        });

        lvProducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                // markAsPurchased(position);
                return true;

            }
        });

    }

    private void markAsPurchased(int position){
        Product p = getProduct(position);
        TextView item = (TextView) findViewById(R.id.textview_product_name);

        if (p.getPurchased() == 0){
            p.setPurchased(1);  //mark as a purchased
            item.setPaintFlags(item.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        }
        else{
            p.setPurchased(0);  //mark as a purchased
            item.setPaintFlags(item.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
        }
        editProduct(p); //makes de update
        loadProducts();
    }

    private void editProduct(Product product){
        dbManager.updateProduct(product);
    }

    private void goToNewProduct(Product p){
        Intent intent = new Intent(this,NewProductActivity.class);
        Bundle b = new Bundle();
        b.putBoolean("editMode",true);
        b.putParcelable("product", p);
        intent.putExtras(b);
        startActivity(intent);
    }

    private void creaNuevaLista(){
        Intent i = new Intent(this,NewProductActivity.class);
        Bundle b = new Bundle();
        b.putParcelable("productList", productList);
        i.putExtras(b);
        startActivityForResult(i, 0);

    }

    private void loadProducts(){
        cursor = dbManager.getAllProductsWithCursor(productList);
        productAdapter = new ProductAdapter(this,cursor);
        lvProducts.setAdapter(productAdapter);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (v.getId() == R.id.listViewProducts){
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.prodcut_view_context_menu,menu);
        }

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()){
            case R.id.delete_id:
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
}

And this is the adapter that I'm using

 public class ProductAdapter extends CursorAdapter {
    private LayoutInflater inflater;


    //Constructor
    public ProductAdapter(Context context, Cursor cursor) {
        super(context, cursor,false);
    }

    // The newView method is used to inflate a new view and return it,
    // you don't bind any data to the view at this point.
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.layout_product_row,parent,false);
        return view;
    }

    // The bindView method is used to bind all data to a given view
    // such as setting the text on a TextView.
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView tv_product_name = (TextView) view.findViewById(R.id.textview_product_name); // Find fields to populate in inflated template
        String product_name = cursor.getString(cursor.getColumnIndexOrThrow("name"));// Extract properties from cursor
        // Populate fields with extracted properties
        tv_product_name.setText(product_name);
        if (cursor.getInt(cursor.getColumnIndexOrThrow("purchased")) == 1){
            tv_product_name.setPaintFlags(tv_product_name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        }
    }

    public Product getProduct(int position, Cursor cursor) {
        Product p=null;
        if(cursor.moveToPosition(position)) {
            Log.e("PRODUCTLISTADAPTER","nombre es: "+cursor.getString(cursor.getColumnIndex("name")));
            p = new Product (cursor.getLong(cursor.getColumnIndex("_id")),cursor.getString(cursor.getColumnIndex("name")),
                    cursor.getString(cursor.getColumnIndex("unit_type")),cursor.getDouble(cursor.getColumnIndex("value")),cursor.getInt(cursor.getColumnIndex("purchased")),cursor.getLong(cursor.getColumnIndex("id_pl")));
        }
        return p;
    }
}

Can anyone exaplin me why it isn't working? isn't it necessary to make something on the LongClickListener ? because I don't see that the menu is being created.

Thanks in advance.


Solution

  • You've set an OnItemLongClickListener for the ListView, which will run before the context Menu is created. Returning true from its onItemLongClick() method indicates that the long click is being consumed there, so the Menu will not be created.

    If you don't actually need the OnItemLongClickListener, you can remove the relevant code. If you do need it as well, for some reason, you can return false from onItemLongClick(), and your Menu will then show.