Opening PlacePicker on SearchView single click

91 views Asked by At

I'm using SearchView as below in my code :

xml :

<android.support.v7.widget.SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="false"
        android:focusable="false"
        app:iconifiedByDefault="false"
        app:queryBackground="@color/transparant"
        app:queryHint="@string/search"
        app:searchIcon="@drawable/ic_search">

Java :

 mSearchView = (SearchView) rootView.findViewById(R.id.searchView);
 txtSearchText = (TextView) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
 txtSearchText.setOnClickListener(this);

onCLick :

case R.id.search_src_text:
     loadPlacePicker();
break;

But, the issue is SearchView needs a double click to open up PlacePicker. I need to open PlacePicker on the single onClick Event of SearchView. How do I do that?

2

There are 2 answers

2
Mohit Kalia On

Use this.

import android.annotation.TargetApi;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListAdapter;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class LocationAutoCompletePRMView extends AutoCompleteTextView implements AdapterView.OnItemClickListener
{
    GetCityHelperG_          GET_CITY_G;
    SelectedLocationListener selectedLocationListener;

public LocationAutoCompletePRMView(Context context)
{
    super(context);
}

public LocationAutoCompletePRMView(Context context, AttributeSet attrs)
{
    super(context, attrs);
}

public LocationAutoCompletePRMView(Context context, AttributeSet attrs, int defStyleAttr)
{
    super(context, attrs, defStyleAttr);
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public LocationAutoCompletePRMView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
{
    super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
public <T extends ListAdapter & Filterable> void setAdapter(T adapter)
{
    super.setAdapter(adapter);
}

public void startLocationAdapter(Context con, SelectedLocationListener selectedLocationListener)
{
    this.selectedLocationListener = selectedLocationListener;
    GET_CITY_G = new GetCityHelperG_(con, android.R.layout.simple_list_item_1);
    this.setAdapter(GET_CITY_G);
    this.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l)
{
    Latlng_data resultList = GET_CITY_G.set_LAT_Lng_value(position);
    selectedLocationListener.onResult(resultList);
}

// *************************************************************  INTERFACE FOR SENDING THE SELECTED LOCATION DATA BACK TO THE CALLING CLASS  ******************************************************************


public interface SelectedLocationListener
{
    public void onResult(Latlng_data latLongModel);
}

// *********************************************************  ADAPTER  **********************************************************************

public class GetCityHelperG_ extends ArrayAdapter<String> implements Filterable
{
    public List<Latlng_data> resultList = new ArrayList<>();
    private Context con;

    public GetCityHelperG_(Context context, int textViewResourceId)
    {

        super(context, textViewResourceId);
        con = context;
    }

    @Override
    public int getCount()
    {
        return resultList.size();
    }

    @Override
    public String getItem(int index)
    {
        try
        {
            return resultList.get(index).getAddress();
        }
        catch (Exception e)
        {

        }
        return "";
    }

    @Override
    public Filter getFilter()
    {
        Filter filter = new Filter()
        {
            @Override
            protected FilterResults performFiltering(final CharSequence constraint)
            {
                FilterResults filterResults = new FilterResults();
                if (constraint != null)
                {
                    if (!fetchingAddress)
                    {
                        resultList = GetAddressByString(con, constraint.toString());
                    }

                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results)
            {
                try
                {
                    if (results != null && results.count > 0)
                    {
                        notifyDataSetChanged();
                    }
                    else
                    {
                        notifyDataSetInvalidated();
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        };
        return filter;
    }


    boolean fetchingAddress = false;

    private List<Latlng_data> GetAddressByString(Context con, final String addressssss)
    {
        fetchingAddress = true;
        String   addressReturn = "";
        Geocoder geocoder      = new Geocoder(con, Locale.getDefault());

        List<Latlng_data> dataList = new ArrayList<>();


        List<Address> addresses;
        try
        {
            addresses = geocoder.getFromLocationName(addressssss, 3);

            Latlng_data l = null;

            for (int i = 0; i < addresses.size(); i++)
            {

                int getMAxAddrss = addresses.get(i).getMaxAddressLineIndex();

                for (int g = 0; g < getMAxAddrss; g++)
                {
                    addressReturn = addressReturn + "," + addresses.get(i).getAddressLine(g);
                }
                addressReturn = addressReturn.substring(1, addressReturn.length());
                l = new Latlng_data();
                l.setAddress(addressReturn);
                l.setLat(addresses.get(0).getLatitude());
                l.setLng(addresses.get(0).getLongitude());
                addressReturn = "";

                dataList.add(l);
            }
            if (addresses.isEmpty())
            {
                dataList = getLocationFromString(addressssss);
            }
        }
        catch (Exception e)
        {
            dataList = getLocationFromString(addressssss);

        }
        catch (Error e)
        {
            dataList = getLocationFromString(addressssss);
        }
        fetchingAddress = false;


        return dataList;

    }


    // Directly access google map for location
    public List<Latlng_data> getLocationFromString(String address)
    {

        List<Latlng_data> Ldata = new ArrayList<Latlng_data>();

        try
        {
            String URL = "http://maps.google.com/maps/api/geocode/json?address=" + URLEncoder.encode(address, "UTF-8") + "&en&sensor=false";

            JSONObject jsonObject = new JSONObject(new WebServiceHandler().performGetCall(URL));

            JSONArray results = jsonObject.getJSONArray("results");

            Latlng_data l;
            for (int j = 0; j < results.length(); j++)
            {

                l = new Latlng_data();

                double lng = results.getJSONObject(j).getJSONObject("geometry").getJSONObject("location").getDouble("lng");

                double lat = results.getJSONObject(j).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
                String addrsssssName = results.getJSONObject(j).getString("formatted_address");
                l.setAddress(addrsssssName != null ? addrsssssName : "");

                l.setLat(lng);
                l.setLng(lat);

                Ldata.add(l);
            }

        }
        catch (Exception e)
        {
            return Ldata;
        }
        catch (Error e)
        {
            return Ldata;
        }

        return Ldata;
    }

    public Latlng_data set_LAT_Lng_value(int position)
    {
        return resultList.get(position);
    }


}

// *************************************************************  LATITUDE LONGITUDE MODEL  ******************************************************************
    public class Latlng_data
    {
        String address;
        double lat, lng;

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    public double getLat()
    {
        return lat;
    }

    public void setLat(double lat)
    {
        this.lat = lat;
    }

    public double getLng()
    {
        return lng;
    }

    public void setLng(double lng)
    {
        this.lng = lng;
    }
}
// *****************************************************************  WEBSERVICE CLASS FOR GETTINGRESPONSE FROM GOOGLE  **************************************************************
public class WebServiceHandler
{
    public String performGetCall(String url) throws Exception
    {
        URL               obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in       = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String         inputLine;
        StringBuffer   response = new StringBuffer();

        while ((inputLine = in.readLine()) != null)
        {
            response.append(inputLine);
        }
        in.close();

        //print result
        Log.e("== get Call response====".toUpperCase(), response.toString());
        return response.toString(); //this is your response
    }
}

}

XML layout code

 <com.ameba.ptfix.COMMON.WebUtils.LocationAutoCompletePRMView
                    android:id="@+id/tvAutoComplete"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:hint="Type here..."
                    android:maxLength="150"
                    android:padding="5dp"
                    android:textColor="@color/BlackNew"
                    android:textColorHint="@color/grey_medium"
                    android:textSize="@dimen/small_text_size" />
1
Hasan Sajora On

You need to change the value of searchView attribute clickable & focusable to true

<android.support.v7.widget.SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusable="true"
    app:iconifiedByDefault="false"
    app:queryBackground="@color/transparant"
    app:queryHint="@string/search"
    app:searchIcon="@drawable/ic_search">