我试图打开上下文菜单,并使用registerForContectMenu() 在onCreate()以及onCreateContextMenu()和onContextItemSelected()中,由于我单击每个项目时没有任何反应,因此发生了错误。
ListView listView;
ArrayAdapter<Product> productArrayAdapter;
List<Product> productList;
String catagory;
TextView txtTitle;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
listView = (ListView)findViewById(R.id.listView);
productList = new ArrayList<>();
Bundle b = new Bundle();
b = getIntent().getExtras();
catagory = b.getString("catagory");
txtTitle = (TextView)findViewById(R.id.txtTitle);
txtTitle.setText("Ours "+catagory+" Collection");
registerForContextMenu(listView);
}
此代码用于将Firebase数据库中的数据显示到列表视图中
@Override
protected void onStart() {
super.onStart();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference(catagory);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
productList.clear();
for(DataSnapshot d : dataSnapshot.getChildren())
{
if(catagory.equals("Doors")) {
Doors door = d.getValue(Doors.class);
productList.add(door);
}
if(catagory.equals("Locks")) {
Locks lock = d.getValue(Locks.class);
productList.add(lock);
}
if(catagory.equals("Remotes")) {
Remotes remote = d.getValue(Remotes.class);
productList.add(remote);
}
}
productArrayAdapter = new ProductAdapter(CatalogActivity.this, productList, catagory);
listView.setAdapter(productArrayAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
所有需要的ContextMenu函数
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId() == R.id.listView) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
}
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
//all toasts is just for check if it works
switch (item.getItemId()){
case R.id.buyNow:
Toast.makeText(getApplicationContext(),"now",
Toast.LENGTH_LONG).show();
return true;
case R.id.addToCart:
Toast.makeText(getApplicationContext(),"cart",
Toast.LENGTH_LONG).show();
return true;
case R.id.saveForLater:
Toast.makeText(getApplicationContext(),"later",
Toast.LENGTH_LONG).show();
return true;
default:
return super.onContextItemSelected(item);
}
}