编程语言
首页 > 编程语言> > java-当用户单击autocom时如何显示HashMap键的值

java-当用户单击autocom时如何显示HashMap键的值

作者:互联网

我是android开发和Java编程的新手.在我的代码中(如下所示),当用户单击搜索按钮时,键的值将显示在displayField TextView中.但是我想要它,以便用户单击(触摸)AutoCompleteTextView下拉菜单项时显示该值,而无需单击搜索按钮.

import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity 
{   

    Map<String, String> map = new HashMap<String, String>();

    private EditText autocomplete_searchField;
    private TextView displayField;
    String note;

    @Override
    protected  void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    autocomplete_searchField = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);

    // Get a reference to the AutoCompleteTextView in the layout
    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);

    // Gets the string array
    String[] music_note = getResources().getStringArray(R.array.music_notes_array);

    // Creates the adapter and set it to the AutoCompleteTextView 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, musicNote);
    textView.setAdapter(adapter);

    displayField = (TextView) findViewById(R.id.displayField);
    Button button = (Button)findViewById(R.id.button); // I want to completely remove this button eventually
    button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String note = autocomplete_searchField.getText().toString();
            displayField.setText(map.get(note));


    map.put("Doe", "a deer, a female deer");
    map.put("Ray", "a drop of golden sun");
}

解决方法:

无论如何,我不明白为什么您需要在代码中使用autocomplete_searchField,如果我很好理解,您只需要删除button.setOnClickListener并添加以下代码即可:

textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

        displayField.setText(map.get(adapterView.getItemAtPosition(position).toString()));

    }

});

标签:autocompletetextview,hashmap,java,android
来源: https://codeday.me/bug/20191028/1950810.html