在Android的地理codeR自动完成 [英] Geocoder autocomplete in android

查看:113
本文介绍了在Android的地理codeR自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在谷歌上搜索我试图找人有同样的问题,因为我的屁股,没有运气。因此,这里是我的问题:

I've been googling my ass of trying to find someone that are having the same problem as me, without luck. So here's my problem:

我想实现地址的自动完成建议,作为用户类型使用地理codeR Android中一个地方的名字。我想这样的行为大致相同使用combbox JavaScript版本。

I'm trying to implement a autocomplete suggestion of addresses as the user types the name of a place using the geocoder in Android. I want this to behave much the same as the javascript version using a combbox.

我使用的是布局的AutoCompleteTextView,和arrayadapter动态地更新suggestionlist作为用户类型。我已经添加了从什么时候收到onTextChanged()事件调用地理coder.getFromLocationName是使用处理程序调用之前500ms的延迟。如果在500毫秒用户类型的详细信,最后的活动将被取消。我遇到的问题是,建议几乎从未在UI中下拉selectables显示。我得到的地址的建议,但是当我将它们添加到连接到autocomplatetextview适配器他们简单的将不会显示。

I am using a layout with an AutoCompleteTextView, and an arrayadapter to dynamically update the suggestionlist as the user types. I have added a 500ms delay from when the onTextChanged() event is received before a call to the geocoder.getFromLocationName is called using a Handler. If a user types more letter within 500ms, the last event will be cancelled. The problem I am encountering is that the suggestions almost never show up in the UI as selectables in the dropdown. I get the address suggestions, but when I add them to the adapter attached to the autocomplatetextview they simple wont show.

我在一个使用仿真器API级别7上运行这一点,与谷歌的API包括在内。

I'm running this on an emulator using API level 7, with google apis included.

现在一些源$ C ​​$ C来帮助你: 布局:

Now some source code to aid you: The layout:

<LinearLayout android:id="@+id/searchInputLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="6dip"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/searchMessage" />
    <EditText android:id="@+id/freetextInput" 
        android:hint="@string/searchFreetextLabel"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:background="@android:drawable/editbox_background" />
    <CheckBox android:id="@+id/includeVincinityCheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/includeVincinityLabel"
        android:checked="true"
        android:onClick="includeVincinityClick" />
    <AutoCompleteTextView android:id="@+id/locationInput" 
        android:hint="@string/locationInputHint"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" />
    <Button android:id="@+id/searchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/searchBtnLabel" 
        android:onClick="searchBtnClicked" />
    </LinearLayout>

我活动的源头code(我省略了$ C $无关C):

The source code of my activity (I've omitted code not relevant):

public class SearchLocationTabActivity extends Activity implements TextWatcher, OnItemSelectedListener {

private static final int MESSAGE_TEXT_CHANGED = 0;
private static final int AUTOCOMPLETE_DELAY = 500;
private static final int THRESHOLD = 3;
private String latitude, longitude;
private List<Address> autoCompleteSuggestionAddresses;
private ArrayAdapter<String> autoCompleteAdapter;
private Handler messageHandler;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.search);
    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

    messageHandler = new MyMessageHandler(this, this);
    autoCompleteAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, new ArrayList<String>());
    autoCompleteAdapter.setNotifyOnChange(false);
    AutoCompleteTextView locationinput = (AutoCompleteTextView) findViewById(R.id.locationInput);
    locationinput.addTextChangedListener(this);
    locationinput.setOnItemSelectedListener(this);
    locationinput.setThreshold(THRESHOLD);
    locationinput.setAdapter(autoCompleteAdapter);
}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    messageHandler.removeMessages(MESSAGE_TEXT_CHANGED);
}

@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
String value = arg0.toString();
if (!"".equals(value) && value.length() >= THRESHOLD) {
    Message msg = Message.obtain(messageHandler, MESSAGE_TEXT_CHANGED, arg0.toString());
    messageHandler.sendMessageDelayed(msg, AUTOCOMPLETE_DELAY);
} else {
    autoCompleteAdapter.clear();
}
}

@Override
public void afterTextChanged(Editable arg0) {
}

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    if (arg2 < autoCompleteSuggestionAddresses.size()) {
        Address selected = autoCompleteSuggestionAddresses.get(arg2);
        latitude = Double.toString(selected.getLatitude());
        longitude = Double.toString(selected.getLongitude());
    }
}

private void notifyResult(List<Address> suggestions) {
    latitude = longitude = null;
    autoCompleteAdapter.clear();
    for (Address a : autoCompleteSuggestionAddresses) {
        autoCompleteAdapter.add(a.toString());//TODO: figure out a nice way to display this address in list
    }
    autoCompleteAdapter.notifyDataSetChanged();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    latitude = longitude = null;
}

private class MyMessageHandler extends Handler {

    private Context context;
    private AsyncTaskSubscriber subscriber;

    public MyMessageHandler(Context context, AsyncTaskSubscriber subscriber) {
        this.context = context;
        this.subscriber = subscriber;
    }

    @Override
    public void handleMessage(Message msg) {
        if (msg.what == MESSAGE_TEXT_CHANGED) {
            String enteredText = (String) msg.obj;

            try {
                autoCompleteSuggestionAddresses = new Geocoder(context).getFromLocationName(enteredText, 10);

                notifyResult(response);
            } catch (IOException ex) {
                Log.e(GeoCoderAsyncTask.class.getName(), "Failed to get autocomplete suggestions", ex);
            }
        }
    }
}
}

任何帮助是非常AP preciated!

Any help is much appreciated!

推荐答案

对于那些谁没有设法去除过滤,这里是我做了什么(还有其他小的修改,但我不认为他们有一定的影响在过滤部分)。这也说明了该项目的点击进行检测,你需要添加一个OnItemClickListener

For those who did not managed to remove the filtering, here is what I've done (among other small modifications but I don't think they have an impact on the filtering part). Note also that for a click on one of the item to be detected, you need to add an OnItemClickListener.

autoCompleteAdapter = new ArrayAdapterNoFilter(this, android.R.layout.simple_dropdown_item_1line);

在哪里ArrayAdapterNoFilter从激发了我其他的答案

public class ArrayAdapterNoFilter extends ArrayAdapter<String> {

    public ArrayAdapterNoFilter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    private static final NoFilter NO_FILTER = new NoFilter();

    /**
     * Override ArrayAdapter.getFilter() to return our own filtering.
     */
    @Override
    public Filter getFilter() {
        return NO_FILTER;
    }

    /**
     * Class which does not perform any filtering. Filtering is already done by
     * the web service when asking for the list, so there is no need to do any
     * more as well. This way, ArrayAdapter.mOriginalValues is not used when
     * calling e.g. ArrayAdapter.add(), but instead ArrayAdapter.mObjects is
     * updated directly and methods like getCount() return the expected result.
     */
    private static class NoFilter extends Filter {
        protected FilterResults performFiltering(CharSequence prefix) {
            return new FilterResults();
        }

        protected void publishResults(CharSequence constraint, FilterResults results) {
            // Do nothing
        }
    }
}

这篇关于在Android的地理codeR自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆