<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <AutoCompleteTextView android:id="@+id/text1" android:layout_width="280dp" android:layout_height="wrap_content" android:textSize="15dp"/> </LinearLayout>
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | AutoCompleteTextView text1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); text1 = (AutoCompleteTextView ) findViewById(R.id.text1); text1.setThreshold(3); text1.setAdapter(new CustomAdapter(this,android.R.layout.simple_list_item_1)); } private ArrayList<String> getAddressInfo(String locationName) { ArrayList<String> list = new ArrayList<>(); Geocoder geocoder = new Geocoder(this, Locale.getDefault()); try { List<Address> a = geocoder.getFromLocationName(locationName, 5); for (int i = 0; i < a.size(); i++) { String city = a.get(i).getLocality(); String country = a.get(i).getCountryName(); String address = a.get(i).getAddressLine(0); list.add(address +(city!=null?", " + city :"") +(country!=null? ", " + country:"") ); } } catch (IOException e) { e.printStackTrace(); } return list; } class CustomAdapter extends ArrayAdapter implements Filterable { private ArrayList<String> resultList; public CustomAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } @Override public int getCount() { return resultList.size(); } @Override public String getItem(int index) { return resultList.get(index); } @Override public Filter getFilter() { Filter filter = new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); if (constraint != null) { // Retrieve the autocomplete results. resultList = getAddressInfo(constraint.toString()); // Assign the data to the FilterResults filterResults.values = resultList; filterResults.count = resultList.size(); } return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { if (results != null && results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } }; return filter; } } |
No comments:
Post a Comment