在Android的ListActivity中实现上下文菜单,可以通过以下步骤实现:
以下是一个简单的示例代码:
public class MyAdapter extends BaseAdapter {
private Context mContext;
private List<String> mData;
public MyAdapter(Context context, List<String> data) {
mContext = context;
mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.text_view);
holder.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 创建上下文菜单
registerForContextMenu(v);
// 显示上下文菜单
openContextMenu(v);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
private static class ViewHolder {
TextView textView;
}
}
在ListActivity中使用MyAdapter:
public class MyListActivity extends ListActivity {
private List<String> mData = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 添加一些数据
mData.add("Item 1");
mData.add("Item 2");
mData.add("Item 3");
MyAdapter adapter = new MyAdapter(this, mData);
setListAdapter(adapter);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// 添加菜单项
MenuItem menuItem1 = menu.add("Menu Item 1");
MenuItem menuItem2 = menu.add("Menu Item 2");
// 为菜单项设置OnClickListener
menuItem1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// 执行相应的操作
return true;
}
});
menuItem2.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// 执行相应的操作
return true;
}
});
}
}
这样,在ListActivity中的每个列表项上点击时,就会显示一个上下文菜单,其中包含两个菜单项。
领取专属 10元无门槛券
手把手带您无忧上云