当我按退格键时,AutoCompleteTextView会显示建议列表

时间:2012-09-07 05:52:32

标签: android autocompletetextview

我的代码正在关注......

public class NameListActivity extends Activity implements TextWatcher {
    private Button add = null;
    private AutoCompleteTextView editAuto = null;
    private Button chfrlist = null;
    private ImageView im = null;
    String access_token = new String();
    private ImageView infobtn = null;
    private PopupWindow popupWindow;
    private View view;
    private ProgressDialog pd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_name_list);
        access_token = MainService.readToken();

        add = (Button) findViewById(R.id.add_button);
        editAuto = (AutoCompleteTextView) findViewById(R.id.editAuto);
        chfrlist = (Button) findViewById(R.id.chfrlistbutton);
        im = (ImageView) findViewById(R.id.helpact);
        im.setOnClickListener(new ImageListener());
        infobtn = (ImageView) findViewById(R.id.informbtn);
        initPopupWindow();
        infobtn.setOnClickListener(new infobtnListener());
        editAuto.addTextChangedListener(this);
        add.setOnClickListener(new addListener());
        chfrlist.setOnClickListener(new ChfrListListener());
    }

    public class addListener implements OnClickListener {

        public void onClick(View v) {
            addTask task = new addTask();
            task.execute();
            editAuto.setText("");
        }
    }

    public void afterTextChanged(Editable arg0) {

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        onTextChangedTask task = new onTextChangedTask();
        task.execute();
    }

    public class onTextChangedTask extends AsyncTask<Void, Void, Void> {

        ArrayAdapter<String> adapter = null;
        String[] userName = null;
        String q = null;
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        ArrayList<String> userNameArrayList = new ArrayList<String>();
        Weibo weibo = new Weibo();

        @Override
        protected void onPreExecute() {
            weibo.setToken(access_token);
            q = editAuto.getText().toString();
            System.out.println("start onTextChanged");
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            if (q.length() != 0) {
                System.out.println("q is " + q);

                String s1 = "https://api.weibo.com/search/suggestions/users.json";
                try {
                    jsonArray = Weibo.client.get(s1,
                            new PostParameter[] { new PostParameter("q", q) })
                            .asJSONArray();
                } catch (Throwable e) {
                    System.out.println("这里有个神马异常呢 。。。" + e);
                }

                System.out.println("return length is " + jsonArray.length());

                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
                        jsonObject = jsonArray.getJSONObject(i);
                        String sname = jsonObject.getString("screen_name");
                        userNameArrayList.add(sname);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                userName = (String[]) userNameArrayList
                        .toArray(new String[userNameArrayList.size()]);

                adapter = new ArrayAdapter<String>(NameListActivity.this,
                        android.R.layout.simple_dropdown_item_1line, userName);

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            System.out.println("post");
            editAuto.setAdapter(adapter);
        }
    }

    void showToast(String s) {
        Toast toast = Toast.makeText(getApplicationContext(), s,
                Toast.LENGTH_LONG);
        toast.show();
    }

    public class addTask extends AsyncTask<Void, Void, Void> {

        String s = null;
        boolean flag = false;
        User user = null;
        Weibo weibo = new Weibo();
        String screen_name = null;

        protected void onPreExecute() {
            Toast tt = Toast.makeText(getApplicationContext(), "正在将用户添加到备份名单",
                    Toast.LENGTH_LONG);
            tt.setGravity(Gravity.CENTER, 0, 0);
            tt.show();
            weibo.setToken(access_token);
            screen_name = editAuto.getText().toString();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            if (screen_name.length() != 0) {
                Users um = new Users();
                try {
                    user = new User(Weibo.client.get(
                            "https://api.weibo.com/users/show.json",
                            new PostParameter[] { new PostParameter(
                                    "screen_name", screen_name) })
                            .asJSONObject());
                } catch (Throwable e) {
                    e.printStackTrace();
                    flag = true;
                    s = new String("您输入的这个用户好像不存在唉");
                }
                if (user != null) {
                    ContentValues values = new ContentValues();
                    values.put("uid", user.getId());
                    values.put("user_name", user.getName());
                    SQLiteDatabase db = null;
                    try {
                        db = MainService.getDatabase();
                    } catch (Exception e) {
                        System.out.println("db error");
                        finish();
                    }
                    Cursor result = db.query("users", new String[] { "uid",
                            "user_name" }, "uid=?",
                            new String[] { user.getId() }, null, null, null);
                    if (result.getCount() == 0)
                        db.insert("users", null, values);
                } else {
                    flag = true;
                    s = new String("网络存在问题,检查一下吧");
                }
            } else {
                flag = true;
                s = new String("框里输入点东西才能添加啊");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            if (flag == true) {
                System.out.println("要打印的是" + s);
                showToast(s);
            }
        }
    }

    public class infobtnListener implements OnClickListener {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            System.out.println("点击了图片");
            ColorDrawable cd = new ColorDrawable(-0000);
            popupWindow.setBackgroundDrawable(cd);
            // popupWindow.showAsDropDown(v);
            popupWindow.showAtLocation(findViewById(R.id.informbtn),
                    Gravity.LEFT | Gravity.BOTTOM, 0, 100);
        }
    }

    public class ImageListener implements OnClickListener {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            // Intent t = new Intent(NameListActivity.this,
            // GridLayoutActivity.class);
            // startActivity(t);
            finish();
        }

    }

    public class ChfrListListener implements OnClickListener {

        public void onClick(View v) {
            if ((haveInternet() == true)
                    && (GridLayoutActivity.hasAccessToken() == true)) {
                // TODO Auto-generated method stub
                pd = ProgressDialog.show(NameListActivity.this, "",
                        "正在从服务器上获取数据,可能需要较长时间,请耐心等待 ...");
                /* 开启一个新线程,在新线程里执行耗时的方法 */
                new Thread(new Runnable() {
                    public void run() {
                        Intent t = new Intent(NameListActivity.this,
                                ChooseFromListActivity.class);
                        startActivity(t);
                        finish();

                        handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
                    }
                }).start();
            } else {
                Intent t = new Intent(NameListActivity.this,
                        WebViewActivity.class);
                startActivity(t);
                finish();
            }
        }
    }

    private void initPopupWindow() {
        view = getLayoutInflater().inflate(R.layout.namewindow, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        // 这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。
        popupWindow.setOutsideTouchable(true);// 不能在没有焦点的时候使用
    }

    private boolean haveInternet() {
        NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (info == null || !info.isConnected()) {
            return false;
        }
        if (info.isRoaming()) {
            // here is the roaming option you can change it if you want to
            // disable internet while roaming, just return false
            return true;
        }
        return true;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
            pd.dismiss();// 关闭ProgressDialog
        }
    };

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_name_list, menu);
        return true;
    }
}

我的问题是:当我在EditText中输入单词时,没有任何反应。但是当我按退格键时,AutoCompleteTextView会显示建议列表......问题出在editAuto.setAdapter(adapter);

有什么问题?

2 个答案:

答案 0 :(得分:1)

在您的代码中进行以下更改

1)而不是

private AutoCompleteTextView editAuto = null;只是写private AutoCompleteTextView editAuto;

2)将此行添加到onCrate()

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, <your array name here>);

并从onTextChangedTask()

中删除此行

ArrayList<String> userNameArrayList = new ArrayList<String>();

3)将此行添加到onCrate()

editAuto.setAdapter(adapter);

答案 1 :(得分:1)

我知道这已经晚了但是对于那些面临类似问题的人来说,解决方案就是在你想要的时候显示autoCompleteTextView下拉,即点击按钮或onTextChanged。为autoCompleteTextView设置ArrayAdapter后,只需输入以下行。

autoCompleteTextView.showDropDown();