在ListView上打开Longclick上下文菜单

时间:2016-01-25 14:14:01

标签: android contextmenu android-arrayadapter

我有一个简单的上下文菜单,我想制作一个Toast来显示一条短信息。

问题是我无法让项Position显示我想要的具体细节,因为适配器的Position超出了范围。

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

我假设因为您似乎想知道用户长按哪个项目并想知道项目位置,以便您可以从适配器或列表中获取值。 如果我理解你正确的PFB解决方案

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

现在你有了价值,你可以玩它。恩乔伊!

快乐编码!!!