gpt4 book ai didi

android - 在 Android 中打开 float 菜单(上下文菜单)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:37:37 24 4
gpt4 key购买 nike

我创建了一个新菜单,命名为 drmenu.xml。当我按下菜单按钮时它工作正常,但当用户按下按钮时我需要打开一个上下文菜单。下面的代码按钮只是显示 toast 。

这是我的 xml 布局:

 <LinearLayout
android:id="@+id/MenuCall"
android:layout_width="90dip"
android:layout_height="match_parent"
android:gravity="right|center_vertical" >
<ImageView
android:id="@+id/MenuCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/imageiew6" />
</LinearLayout>

这是我的java代码:

    final LinearLayout callback_var = (LinearLayout) findViewById(R.id.MenuCall);
registerForContextMenu(callback_var);
callback_var.setOnClickListener(new android.view.View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "this is repeated", Toast.LENGTH_LONG).show();
openContextMenu(callback_var);
}

最佳答案

如果你想创建一个上下文菜单,你必须调用方法 registerForContextMenu() 将它传递给应该与上下文菜单相关联的 View 。

例如,假设将上下文菜单与一个按钮相关联:

Button button = (Button) findViewById(R.id.my_button);
registerForContextMenu(button);

可以在您的 Activity 的 onCreate() 中调用。然后,在同一个 Activity 中,您需要覆盖 onCreateContextMenu() 方法。

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_context_menu, menu);
}

然后您必须实现 onContextItemSelected(),以便在按下上下文菜单中的项目时触发正确的操作:

@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.first_action:
// your first action code
return true;
case R.id.second_action:
// your second action code
return true;
default:
return super.onContextItemSelected(item);
}
}

现在长按按钮会打开您在 your_context_menu.xml 文件中定义的上下文菜单。

考虑到通过长按打开上下文菜单符合 Android 标准 UI,但是如果您希望上下文菜单出现在简单的点击上,您可以查看 here the answer

注意:如前所述here

An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).

关于android - 在 Android 中打开 float 菜单(上下文菜单)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26146818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com