Android:如何使用浮动上下文菜单项单击获取列表项属性

时间:2019-02-02 21:38:15

标签: android contextmenu recycler-adapter

我有一个带有arraylist声明的活动

private ArrayList<Product> products = new ArrayList<Product>();

和onCreate内

products.add(new Product("Product One",100, 1));
products.add(new Product("Product Two",200, 2));
products.add(new Product("Product Three",170, 3));
products.add(new Product("Product Four",220, 4));

ProductAdapter itemsAdapter = new ProductAdapter(this, products);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(itemsAdapter);
registerForContextMenu(listView);

在“产品”类别中:

public class Product {
  private String mProductName;
  private int mProductPrice;
  private int mProductId;

  public Product(String productName, int productPrice, int productId){
    mProductName = productName;
    mProductPrice = productPrice;
    mProductId = productId;
  }

  public String getProductName(){
    return mProductName;
  }

  public int getProducId(){
    return mProductId;
  }

  public int getProductPrice(){
    return mProductPrice;
  }

}

并且适配器很容易获得每个产品的名称和价格并查看列表。现在,在活动中,我像这样创建上下文菜单

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

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}

我怎样才能长压项目属性如产品编号使用“onContextItemSelected”从上下文菜单中选择optipn后?

1 个答案:

答案 0 :(得分:1)

首先设置全局变量productId,然后在listview上长按侦听器设置产品ID。看看下面的示例代码。

int productId = 0;
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, 
    View arg1,int pos, long id) {
        // TODO Auto-generated method stub
           Product product =  
           (Product)arg0.getAdapter().getItem(position)
           productId = product.mProductId; 
           return false;
        }
    });