其他分享
首页 > 其他分享> > Android 上下文菜单 ContextMenu

Android 上下文菜单 ContextMenu

作者:互联网

public class MainActivity extends Activity {

    private ListView listView;

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

        listView = (ListView) this.findViewById(R.id.listView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,
                getData());
        listView.setAdapter(adapter);

        // 给listView注册上下文菜单
        registerForContextMenu(listView);
    }

    public List<String> getData() {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 7; i++) {
            list.add("thomas " + i);
        }

        return list;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);

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

    // 上下文菜单被选择
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.action_add:
            Toast.makeText(this, "添加被点击", 1).show();
            break;
        case R.id.action_delete:
            Toast.makeText(this, "删除被点击", 1).show();
            break;

        default:
            break;
        }

        return super.onContextItemSelected(item);
    }
}
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_add"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="添加">
    </item>
    <item
        android:id="@+id/action_delete"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="删除">
    </item>

</menu>

长按效果

image

选择菜单

image

标签:上下文,ContextMenu,menu,list,item,Override,Android,listView,public
来源: https://www.cnblogs.com/zhangxuechao/p/11791719.html