输入内容后,我会得到一个自动完成预测。就像我输入“ Joh”时一样,我得到“ John F. Kennedy”。现在,如果用户单击“约翰·肯尼迪”,它将带他进入一个活动,该活动向他提供有关约翰·肯尼迪的信息。我该怎么做?如何使自动完成预测可点击?

package com.mavenmaverick.autocomplete_test;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;


public class MainActivity extends Activity {

String[] presidents= { "John F. Kennedy",
                    "Lyndon B. Johnson",
                    "Richard Nixon",
                    "Gerald Ford",
                    "Jimmy Carter",
                    "Ronald Reagan",
                    "George H. W. Bush",
                    "Bill Clinton",
                    "George W. Bush",
                    "Barack Obama"
                    };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, presidents);

    textView.setThreshold(3);
    textView.setAdapter(adapter);

}

}

最佳答案

使用此代码。

String[] presidents= { "John F. Kennedy",
                    "Lyndon B. Johnson",
                    "Richard Nixon",
                    "Gerald Ford",
                    "Jimmy Carter",
                    "Ronald Reagan",
                    "George H. W. Bush",
                    "Bill Clinton",
                    "George W. Bush",
                    "Barack Obama"
                    };
private AutoCompleteTextView myAutoComplete;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        myAutoComplete = (AutoCompleteTextView) findViewById(R.id.myautocomplete);
        myAutoComplete.addTextChangedListener(this);
        myAutoComplete.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, presidents));



myAutoComplete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getBaseContext(), InforActivity.class);
                    intent.putExtra("president_name", obj.toString());
                    startActivity(intent);
                    finish();

            }
        });

}

10-08 17:40