SearchView始终在自定义渲染器中为空

时间:2014-10-29 04:59:18

标签: xamarin xamarin.android xamarin.forms

我正在尝试在自定义渲染器中创建一个搜索视图,但它总是返回null我尝试了几种不同的方法,但到目前为止结果相同。现在我已经确定了这一点,因为它至少没有抛出任何其他错误。

我的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <SearchView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/mapSearch"
        android:layout_marginBottom="0.0dp"
        class="Android.Widget.SearchView"/>
    <fragment
        android:id="@+id/mapWithOverlay"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:minWidth="25px"
        android:minHeight="25px"
        class="com.google.android.gms.maps.MapFragment" />
</LinearLayout>

在OnElementChangedMethod

_activity = this.Context as Activity;
_searchView = (SearchView) _activity.FindViewById(Resource.Id.mapSearch);
SetupSearchView();

SetupSearchView方法

public void SetupSearchView()
{
    if (_searchView != null)
    {
        _searchView.QueryTextSubmit += async (sender, e) =>
        {
            Console.WriteLine(e.Query);
        };
    }
}

1 个答案:

答案 0 :(得分:0)

如果这是从之前的问题中遵循 PageRenderer 方法,那么 OnElementChanged 可能会在布局 膨胀之前触发?,给 _searchView 一个 null ,因为在那时无法找到它?

可能有一个更好的处理程序来放置这个初始化逻辑,但我目前还没有在 Xamarin.Forms PageRenderers 上做任何事情。

如果您已经拥有 SearchView 控件,只需之前 执行搜索来自先前搜索的参考?

类似于: -

public void DoSearch()
{
    if (_searchView==null)
    {
        _activity = this.Context as Activity;
        _searchView = (SearchView) _activity.FindViewById(Resource.Id.mapSearch);
        SetupSearchView(); 
    }
    ...
    ...
}

然后至少可以确认它是否与在 OnElementChanged 事件处理程序中过早获取引用有关,表明有一个更好的方法把它放进去?