在Android应用程序中实现类似于Google Maps的搜索栏

gam*_*ofe 3 search android google-maps

我正在构建一个使用Google Maps API的应用程序,并且希望它的顶部具有浮动搜索栏,就像Google Maps应用程序中的那个一样。

我已经找到了位置自动完成功能,但是应用程序不会搜索位置,而是搜索用户将创建的另一种数据。

我还发现了一个名为Float Search View的库,但已经停产了一段时间,因此,我想继续讲下去。我也想手动创建它,因为这是我要学习的第一个Android应用程序。

我尝试SearchView在我的XML中实现:

<android.support.v7.widget.SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:iconifiedByDefault="false"
    app:queryHint="@string/search_hint"
    android:theme="@style/SearchBar"/>
Run Code Online (Sandbox Code Playgroud)

具有白色背景和高程:

<style name="SearchBar">
    <item name="android:background">@color/colorPrimary</item>
    <item name="android:elevation">4dp</item>
</style>
Run Code Online (Sandbox Code Playgroud)

看我是否可以接近它,但是结果很奇怪。

在此处输入图片说明

我尝试了其他方法,例如添加Toolbar,但结果是相同的。

我想要一个结果,就像顶部的Google Maps的搜索栏一样。我该怎么做?

dom*_*der 6

Google Maps UI可能没有什么特别之处。我的猜测是这是全屏MapView之上的自定义视图。通过在与全屏MapView相同的容器中放置类似于工具栏的布局,可以执行类似的操作。

这是一个XML布局,可以帮助您入门:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/red"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_add_24dp" />

            <EditText
                android:hint="Try gas stations, ATMs"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" />

            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_search_24dp" />

        </LinearLayout>

    </android.support.v7.widget.CardView>

</android.support.constraint.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

看起来像这样(假设红色是MapView所在的位置):

Android Studio预览版

在这里,您只需要根据需要设置“工具栏”的样式。

希望有帮助!