android – 如何自定义PlaceAutocomplete小部件对话框设计来列出位置

android – 如何自定义PlaceAutocomplete小部件对话框设计来列出位置,第1张

概述我需要使用google placeAutocomplete小部件在下拉列表中显示地点列表.在这里,我正在根据我的查询来显示场所的对话框,但是我需要为Uber,Ola应用程序中的搜索结果对话框定制设计.在这里我想要像下面的图像的设计.如果有人这样做,请给我你的建议,谢谢提前. 您需要自定义适配器.我在我的项目中实现了这个功能.你可以按照这个. activity_search.xml <?xml ve 我需要使用Google placeautocomplete小部件在下拉列表中显示地点列表.在这里,我正在根据我的查询来显示场所的对话框,但是我需要为Uber,ola应用程序中的搜索结果对话框定制设计.在这里我想要像下面的图像的设计.如果有人这样做,请给我你的建议,谢谢提前.

解决方法 您需要自定义适配器.我在我的项目中实现了这个功能.你可以按照这个.

activity_search.xml

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    androID:ID="@+ID/parent"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:orIEntation="vertical"    androID:background="@color/white">    <relativeLayout        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"        >        <linearLayout            androID:ID="@+ID/search_layout"            androID:layout_wIDth="match_parent"            androID:layout_height="50dp"            androID:gravity="center_vertical"            androID:layout_alignParenttop="true"            androID:background="@drawable/searchbar_bg"            androID:layout_marginleft="@dimen/activity_margin_10"            androID:layout_marginRight="@dimen/activity_margin_10"            androID:layout_margintop="@dimen/activity_margin_10"            androID:orIEntation="vertical">                <relativeLayout                    androID:layout_wIDth="match_parent"                    androID:layout_height="match_parent">                    <EditText                        androID:ID="@+ID/search_et"                        androID:layout_wIDth="match_parent"                        androID:layout_height="match_parent"                        androID:hint="Search"                        androID:singleline="true"                        androID:layout_toleftOf="@+ID/clear"                        androID:imeOptions="actionSearch"                        androID:background="@null"                        androID:drawableleft="@drawable/ic_action_search"                        androID:drawablepadding="@dimen/activity_margin_10"                        androID:paddingleft="@dimen/activity_margin_10"                        androID:paddingRight="@dimen/activity_margin_10"/>                    <ImageVIEw                        androID:ID="@+ID/clear"                        androID:layout_wIDth="wrap_content"                        androID:layout_height="wrap_content"                        androID:src="@drawable/ic_clear"                        androID:layout_alignParentRight="true"                        androID:layout_gravity="right|center_vertical"                        androID:padding="@dimen/activity_margin_16"                        androID:visibility="gone"/>                </relativeLayout>        </linearLayout>        <androID.support.v7.Widget.RecyclerVIEw            androID:ID="@+ID/List_search"            androID:layout_wIDth="match_parent"            androID:layout_height="match_parent"            androID:layout_below="@+ID/search_layout"            androID:layout_above="@+ID/powered_by_Google"            androID:background="@color/white"            androID:layout_margintop="@dimen/activity_margin_10"/>        <ImageVIEw            androID:ID="@+ID/powered_by_Google"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:layout_centerHorizontal="true"            androID:layout_alignParentBottom="true"            androID:padding="@dimen/activity_margin_10"            androID:layout_marginBottom="@dimen/activity_margin_10"            androID:src="@drawable/powered_by_Google_light"/>    </relativeLayout></linearLayout>

SearchActivity.java

package com.androID.dezi.vIEws.rIDer.ActivitIEs;import androID.content.Context;import androID.content.Intent;import androID.os.Bundle;import androID.support.v7.Widget.linearlayoutmanager;import androID.support.v7.Widget.RecyclerVIEw;import androID.text.Editable;import androID.text.TextWatcher;import androID.util.Log;import androID.vIEw.VIEw;import androID.vIEw.VIEw.OnClickListener;import androID.Widget.EditText;import androID.Widget.ImageVIEw;import androID.Widget.linearLayout;import androID.Widget.Toast;import com.androID.dezi.BaseActivity;import com.androID.dezi.R;import com.androID.dezi.adapters.PlaceautocompleteAdapter;import com.androID.dezi.adapters.PlaceautocompleteAdapter.PlaceautoCompleteInterface;import com.androID.dezi.adapters.PlaceSavedAdapter;import com.androID.dezi.adapters.PlaceSavedAdapter.SavedplaceListener;import com.androID.dezi.beans.SavedAddress;import com.androID.dezi.vIEws.rIDer.Fragments.SearchFragment;import com.Google.androID.gms.common.ConnectionResult;import com.Google.androID.gms.common.API.Googleapiclient;import com.Google.androID.gms.common.API.PendingResult;import com.Google.androID.gms.common.API.ResultCallback;import com.Google.androID.gms.location.LocationServices;import com.Google.androID.gms.location.places.Place;import com.Google.androID.gms.location.places.PlaceBuffer;import com.Google.androID.gms.location.places.Places;import com.Google.androID.gms.location.places.ui.Placeautocomplete;import com.Google.androID.gms.maps.GoogleMap;import com.Google.androID.gms.maps.OnMapReadyCallback;import com.Google.androID.gms.maps.model.LatLng;import com.Google.androID.gms.maps.model.LatLngBounds;import java.util.ArrayList;import java.util.List;/** * Created by anuj.sharma on 4/6/2016. */public class SearchActivity extends BaseActivity implements PlaceautoCompleteInterface,Googleapiclient.OnConnectionFailedListener,Googleapiclient.ConnectionCallbacks,OnClickListener,SavedplaceListener {    Context mContext;    Googleapiclient mGoogleapiclient;    linearLayout mParent;    private RecyclerVIEw mRecyclerVIEw;    linearlayoutmanager llm;    PlaceautocompleteAdapter mAdapter;    List<SavedAddress> mSavedAddressList;    PlaceSavedAdapter mSavedAdapter;    private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(            new LatLng(-0,0),new LatLng(0,0));    EditText mSearchEdittext;    ImageVIEw mClear;    @OverrIDe    public voID onStart() {        mGoogleapiclient.connect();        super.onStart();    }    @OverrIDe    public voID onStop() {        mGoogleapiclient.disconnect();        super.onStop();    }    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.fragment_search);        mContext = SearchActivity.this;        mGoogleapiclient = new Googleapiclient.Builder(this)                .enableautoManage(this,0 /* clIEntID */,this)                .addAPI(Places.GEO_DATA_API)                .build();        initVIEws();    }    /*   Initialize VIEws    */    private voID initVIEws(){        mRecyclerVIEw = (RecyclerVIEw)findVIEwByID(R.ID.List_search);        mRecyclerVIEw.setHasFixedSize(true);        llm = new linearlayoutmanager(mContext);        mRecyclerVIEw.setLayoutManager(llm);        mSearchEdittext = (EditText)findVIEwByID(R.ID.search_et);        mClear = (ImageVIEw)findVIEwByID(R.ID.clear);        mClear.setonClickListener(this);        mAdapter = new PlaceautocompleteAdapter(this,R.layout.vIEw_placesearch,mGoogleapiclient,BOUNDS_INDIA,null);        mRecyclerVIEw.setAdapter(mAdapter);        mSearchEdittext.addTextChangedListener(new TextWatcher() {            @OverrIDe            public voID beforeTextChanged(CharSequence s,int start,int count,int after) {            }            @OverrIDe            public voID onTextChanged(CharSequence s,int before,int count) {                if (count > 0) {                    mClear.setVisibility(VIEw.VISIBLE);                    if (mAdapter != null) {                        mRecyclerVIEw.setAdapter(mAdapter);                    }                } else {                    mClear.setVisibility(VIEw.GONE);                    if (mSavedAdapter != null && mSavedAddressList.size() > 0) {                        mRecyclerVIEw.setAdapter(mSavedAdapter);                    }                }                if (!s.toString().equals("") && mGoogleapiclient.isConnected()) {                    mAdapter.getFilter().filter(s.toString());                } else if (!mGoogleapiclient.isConnected()) {//                    Toast.makeText(getApplicationContext(),Constants.API_NOT_CONNECTED,Toast.LENGTH_SHORT).show();                    Log.e("","NOT CONNECTED");                }            }            @OverrIDe            public voID afterTextChanged(Editable s) {            }        });    }    @OverrIDe    public voID onClick(VIEw v) {        if(v == mClear){            mSearchEdittext.setText("");            if(mAdapter!=null){                mAdapter.clearList();            }        }    }    @OverrIDe    public voID onConnected(Bundle bundle) {    }    @OverrIDe    public voID onConnectionSuspended(int i) {    }    @OverrIDe    public voID onConnectionFailed(ConnectionResult connectionResult) {    }    @OverrIDe    public voID onPlaceClick(ArrayList<PlaceautocompleteAdapter.Placeautocomplete> mResultList,int position) {        if(mResultList!=null){            try {                final String placeID = String.valueOf(mResultList.get(position).placeID);                        /*                             Issue a request to the Places Geo Data API to retrIEve a Place object with additional details about the place.                         */                PendingResult<PlaceBuffer> placeResult = Places.GeoDataAPI                        .getPlaceByID(mGoogleapiclient,placeID);                placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {                    @OverrIDe                    public voID onResult(PlaceBuffer places) {                        if(places.getCount()==1){                            //Do the things here on Click.....                            Intent data = new Intent();                            data.putExtra("lat",String.valueOf(places.get(0).getLatLng().latitude));                            data.putExtra("lng",String.valueOf(places.get(0).getLatLng().longitude));                            setResult(SearchActivity.RESulT_OK,data);                            finish();                        }else {                            Toast.makeText(getApplicationContext(),"something went wrong",Toast.LENGTH_SHORT).show();                        }                    }                });            }            catch (Exception e){            }        }    }    @OverrIDe    public voID onSavedplaceClick(List<SavedAddress> mResponse,int position) {        if(mResponse!=null){            try {                Intent data = new Intent();                data.putExtra("lat",String.valueOf(mResponse.get(position).getLatitude()));                data.putExtra("lng",String.valueOf(mResponse.get(position).getLongitude()));                setResult(SearchActivity.RESulT_OK,data);                finish();            }            catch (Exception e){            }        }    }}

PlaceautocompleteAdapter.java

这是定制的适配器.所有重要的部分都在这里.

package com.androID.dezi.adapters;import androID.content.Context;import androID.graphics.Typeface;import androID.support.v7.Widget.RecyclerVIEw;import androID.text.style.CharacterStyle;import androID.text.style.StyleSpan;import androID.util.Log;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;import androID.Widget.Filter;import androID.Widget.Filterable;import androID.Widget.ImageVIEw;import androID.Widget.linearLayout;import androID.Widget.relativeLayout;import androID.Widget.TextVIEw;import androID.Widget.Toast;import com.androID.dezi.R;import com.androID.dezi.beans.TripHistoryBean;import com.androID.dezi.vIEws.rIDer.Fragments.SearchFragment;import com.Google.androID.gms.common.API.Googleapiclient;import com.Google.androID.gms.common.API.PendingResult;import com.Google.androID.gms.common.API.Status;import com.Google.androID.gms.common.data.DataBufferUtils;import com.Google.androID.gms.location.places.autocompleteFilter;import com.Google.androID.gms.location.places.autocompletePrediction;import com.Google.androID.gms.location.places.autocompletePredictionBuffer;import com.Google.androID.gms.location.places.Places;import com.Google.androID.gms.maps.model.LatLngBounds;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.concurrent.TimeUnit;/** * Created by anuj.sharma on 4/6/2016. */public class PlaceautocompleteAdapter extends RecyclerVIEw.Adapter<PlaceautocompleteAdapter.PlaceVIEwHolder> implements Filterable{    public interface PlaceautoCompleteInterface{        public voID onPlaceClick(ArrayList<Placeautocomplete> mResultList,int position);    }    Context mContext;    PlaceautoCompleteInterface mListener;    private static final String TAG = "PlaceautocompleteAdapter";    private static final CharacterStyle STYLE_BolD = new StyleSpan(Typeface.BolD);    ArrayList<Placeautocomplete> mResultList;    private Googleapiclient mGoogleapiclient;    private LatLngBounds mBounds;    private int layout;    private autocompleteFilter mPlaceFilter;    public PlaceautocompleteAdapter(Context context,int resource,Googleapiclient Googleapiclient,LatLngBounds bounds,autocompleteFilter filter){        this.mContext = context;        layout = resource;        mGoogleapiclient = Googleapiclient;        mBounds = bounds;        mPlaceFilter = filter;        this.mListener = (PlaceautoCompleteInterface)mContext;    }    /*    Clear List items     */    public voID clearList(){        if(mResultList!=null && mResultList.size()>0){            mResultList.clear();        }    }    /**     * Sets the bounds for all subsequent querIEs.     */    public voID setBounds(LatLngBounds bounds) {        mBounds = bounds;    }    @OverrIDe    public Filter getFilter() {        Filter filter = new Filter() {            @OverrIDe            protected FilterResults performFiltering(CharSequence constraint) {                FilterResults results = new FilterResults();                // Skip the autocomplete query if no constraints are given.                if (constraint != null) {                    // query the autocomplete API for the (constraint) search string.                    mResultList = getautocomplete(constraint);                    if (mResultList != null) {                        // The API successfully returned results.                        results.values = mResultList;                        results.count = mResultList.size();                    }                }                return results;            }            @OverrIDe            protected voID publishResults(CharSequence constraint,FilterResults results) {                if (results != null && results.count > 0) {                    // The API returned at least one result,update the data.                    notifyDataSetChanged();                } else {                    // The API dID not return any results,invalIDate the data set.                    //notifyDataSetInvalIDated();                }            }        };        return filter;    }    private ArrayList<Placeautocomplete> getautocomplete(CharSequence constraint) {        if (mGoogleapiclient.isConnected()) {            Log.i("","Starting autocomplete query for: " + constraint);            // submit the query to the autocomplete API and retrIEve a PendingResult that will            // contain the results when the query completes.            PendingResult<autocompletePredictionBuffer> results =                    Places.GeoDataAPI                            .getautocompletePredictions(mGoogleapiclient,constraint.toString(),mBounds,mPlaceFilter);            // This method should have been called off the main UI thread. Block and wait for at most 60s            // for a result from the API.            autocompletePredictionBuffer autocompletePredictions = results                    .await(60,TimeUnit.SECONDS);            // Confirm that the query completed successfully,otherwise return null            final Status status = autocompletePredictions.getStatus();            if (!status.isSuccess()) {//                Toast.makeText(mContext,"Error contacting API: " + status.toString(),//                        Toast.LENGTH_SHORT).show();                Log.e("","Error getting autocomplete prediction API call: " + status.toString());                autocompletePredictions.release();                return null;            }            Log.i("","query completed. Received " + autocompletePredictions.getCount()                    + " predictions.");            // copy the results into our own data structure,because we can't hold onto the buffer.            // autocompletePrediction objects encapsulate the API response (place ID and description).            Iterator<autocompletePrediction> iterator = autocompletePredictions.iterator();            ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());            while (iterator.hasNext()) {                autocompletePrediction prediction = iterator.next();                // Get the details of this prediction and copy it into a new Placeautocomplete object.                resultList.add(new Placeautocomplete(prediction.getPlaceID(),prediction.getDescription()));            }            // Release the buffer Now that all data has been copIEd.            autocompletePredictions.release();            return resultList;        }        Log.e("","Google Api clIEnt is not connected for autocomplete query.");        return null;    }    @OverrIDe    public PlaceVIEwHolder onCreateVIEwHolder(VIEwGroup vIEwGroup,int vIEwType) {        LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        VIEw convertVIEw = layoutInflater.inflate(layout,vIEwGroup,false);        PlaceVIEwHolder mPredictionHolder = new PlaceVIEwHolder(convertVIEw);        return mPredictionHolder;    }    @OverrIDe    public voID onBindVIEwHolder(PlaceVIEwHolder mPredictionHolder,final int i) {        mPredictionHolder.mAddress.setText(mResultList.get(i).description);        mPredictionHolder.mParentLayout.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw v) {                mListener.onPlaceClick(mResultList,i);            }        });    }    @OverrIDe    public int getItemCount() {        if(mResultList != null)            return mResultList.size();        else            return 0;    }    public Placeautocomplete getItem(int position) {        return mResultList.get(position);    }    /*    VIEw Holder For Trip History     */    public class PlaceVIEwHolder extends RecyclerVIEw.VIEwHolder {        //        CardVIEw mCardVIEw;        public relativeLayout mParentLayout;        public TextVIEw mAddress;        public PlaceVIEwHolder(VIEw itemVIEw) {            super(itemVIEw);            mParentLayout = (relativeLayout)itemVIEw.findVIEwByID(R.ID.predictedRow);            mAddress = (TextVIEw)itemVIEw.findVIEwByID(R.ID.address);        }    }    /**     * Holder for Places Geo Data autocomplete API results.     */    public class Placeautocomplete {        public CharSequence placeID;        public CharSequence description;        Placeautocomplete(CharSequence placeID,CharSequence description) {            this.placeID = placeID;            this.description = description;        }        @OverrIDe        public String toString() {            return description.toString();        }    }}

vIEw_placesearch.xml

要在适配器中显示的自定义视图

<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    androID:ID="@+ID/predictedRow"    androID:layout_wIDth="match_parent"    androID:layout_height="65dp"    androID:layout_marginleft="10dp"    androID:layout_marginRight="10dp"    androID:layout_centerVertical="true"    androID:gravity="center_vertical">    <ImageVIEw        androID:ID="@+ID/image"        androID:layout_wIDth="22dp"        androID:layout_height="22dp"        androID:src="@drawable/ic_action_navigate"        androID:layout_marginleft="10dp"        androID:layout_margintop="20dp"        />    <TextVIEw        androID:ID="@+ID/address"        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:textcolor="#000"        androID:textSize="15sp"        androID:layout_toRightOf="@+ID/image"        androID:layout_centerVertical="true"        androID:layout_marginleft="20dp"        androID:layout_marginRight="20dp"        /><VIEw    androID:layout_wIDth="match_parent"    androID:layout_height="1dp"    androID:background="@color/light_gray"    androID:layout_alignParentBottom="true"/></relativeLayout>

希望它也会帮助你.

注意:
不要忘记在您的清单文件中添加API密钥.

输出将如下:

我找到一些有用的链接,也可以帮助你.

1. Android Plat Places using custom Adapter

总结

以上是内存溢出为你收集整理的android – 如何自定义PlaceAutocomplete小部件对话框设计来列出位置全部内容,希望文章能够帮你解决android – 如何自定义PlaceAutocomplete小部件对话框设计来列出位置所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1131946.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存