当我触摸ListView中的项目列表时,它应该显示上下文菜单。但我没有得到一个。 这是Java代码:
public class MainActivity extends Activity {
ListView listView;
List<String> list=new ArrayList<>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView= (ListView) findViewById(R.id.list_view);
list.add("Strawberry");
list.add("Gooseberry");
list.add("Blueberry");
list.add("Mulberry");
list.add("Raspberry");
adapter=new ArrayAdapter<>
(this,android.R.layout.simple_expandable_list_item_1,list);
listView.setAdapter(adapter);
registerForContextMenu(listView);//pass listView to
registerForContextMenu
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
}
以下是activity_main的XML代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ccc"
android:orientation="vertical"
tools:context="com.iox_prime.menudemo.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MENU DEMO"
android:textColor="#000"
android:textSize="22sp"
android:textStyle="bold" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#999" />
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#999" />
</LinearLayout>
这是菜单的XML:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/delete"
android:title="Delete"/>
<item android:id="@+id/edit"
android:title="Edit"/>
</menu>
执行期间没有错误。但是当我在调试模式下使用断点运行程序时,它会抛出ClassNotFoundException。它说,它无法找到android.widget.ViewStub。请查看此处附带的图片。 enter image description here
答案 0 :(得分:0)
找到答案:事实上,这很简单:上下文菜单从未打算触及。它意味着触摸和持有。我触摸并按住菜单项,它按照我的意愿工作!