Search code examples
androidcontextmenuandroid-arrayadapter

Open context menu on Longclick on ListView


I have a simple context menu and I want to make a Toast to display a short message.

The problem is I can't get the item Position to display the specific detail I want because the Position of the adapter is out of scope.

This is my code:

public class MainActivity extends AppCompatActivity implements     View.OnClickListener {

private ArrayAdapter<Product> adapter;
private ListView listView;
private ContextMenu menu;


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

    listView = (ListView) findViewById(R.id.listView);
    adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
    listView.setAdapter(adapter);

    registerForContextMenu(listView);

    adapter.add(new Product("shoe", 150));
    adapter.add(new Product("T shirt", 80));
    adapter.add(new Product("pants", 100));
    adapter.add(new Product("lamp", 300));
    adapter.add(new Product("ball", 20));
    adapter.add(new Product("egg", 1));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
          Toast.makeText(MainActivity.this, adapter.getItem(position) + ": " + adapter.getItem(position).getPrice(), Toast.LENGTH_SHORT).show();

        }
    });

}


@Override
public void onClick(View v) {

}


@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    menu.setHeaderTitle("choose what to do");
    menu.add(1, 0, 0, "product details");
    menu.add(1,1,1,"delete");

}

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case 0:
            Toast.makeText(MainActivity.this, adapter... + ": " +  adapter..., Toast.LENGTH_SHORT).show();
            break;
    }
    return true;
}
}

Solution

  • I assume because it seems like you wanted to know which item has been long pressed by the user and wanted to know the item position so that you can get the value from Adapter Or List. If I understand you correct PFB solution

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    info.position;//This is your desired position.
    

    now you have the value and you can play with it. Njoy!

    Happy Coding!!!