我的listview上有锁定图标我想在listview上使用longpress隐藏/显示它 我尝试了但是获得了一个nullpointer Exception我该怎么办请帮助 我是android的新手 任何帮助?在此先感谢....
listView = (ListView)findViewById(R.id.lv_filename);
lock =(ImageView)findViewById(R.id.lock);
registerForContextMenu(listView);
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.lv_filename) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list, menu);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.add:
// add stuff here
return true;
case R.id.edit:
lock.setVisibility(View.INVISIBLE); //getting error on this line
default:
return super.onContextItemSelected(item);
}
}
logcat的:
java.lang.NullPointerException
at com.advoco.notepad.MainActivity.onContextItemSelected(MainActivity.java:105)
at android.app.Activity.onMenuItemSelected(Activity.java:2714)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:408)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:113)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4082)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:741)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:884)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:173)
at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:952)
at android.widget.AdapterView.performItemClick(AdapterView.java:302)
at android.widget.AbsListView.performItemClick(AbsListView.java:1196)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3054)
at android.widget.AbsListView$3.run(AbsListView.java:3812)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
findViewById()
方法在您的活动布局中查找具有特定ID的视图。如果找不到该视图,它将返回null。
现在,由于您的身份ImageView
R.id.lock
不在活动布局中,这正是您获得java.lang.NullPointerException
的原因。
您需要在自定义适配器中声明此ImageView
,您可以在其中执行所有可见性操作。