protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
var product = new[] {
"India","Nokia","Dhurv","Gohil","Patel","Sony","Bhaumik","Umang","Riya","Afghanistan","America"
};
var _listView = FindViewById<ListView>(Resource.Id.MylistView);
var _adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, product);
_listView.Adapter = _adapter;
}
public override bool OnCreateOptionsMenu (IMenu menu)
{
MenuInflater.Inflate (Resource.Layout.Menu,menu);
var item = menu.FindItem(Resource.Id.action_search);
var searchView = MenuItemCompat.GetActionView (item);
var _searchView = searchView.JavaCast<SearchView>();
_searchView.QueryTextChange += (s, e) => _adapter.Filter.InvokeFilter(e.NewText);
_searchView.QueryTextSubmit += (s, e) =>
{
// Handle enter/search button on keyboard here
Toast.MakeText(this, "Searched for: " + e.Query, ToastLength.Short).Show();
e.Handled = true;
};
return true;
}
我收到了错误:
_adapter在当前上下文中不存在(在OnCreateOptionsMenu中)
如何解决此错误?
我没有将AppCompat
用于SearchView
。代码好吗?无论如何要解决这个问题吗?
答案 0 :(得分:0)
您无法访问_adapter
中的OnCreateOptionsMenu
,因为它仅在OnCreate
内知道。要在类的其他方法中访问它,您需要使其成为类成员。也许有点像这样:
class MyClass
{
ArrayAdapter<String> _adapter = null;
...
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// ... the rest of your code
_adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, product);
// ...
}
protected override void OnCreateOptionsMenu(IMenu menu)
{
// ... other stuff
_searchView.QueryTextChange += (s, e) => _adapter.Filter.InvokeFilter(e.NewText);
// ...
}
}
请注意var
中_adapter = ...
前面没有OnCreate
。