简体   繁体   English

Android AutoCompleteTextView:获取项目位置

[英]Android AutoCompleteTextView: get item position

I'm creating a custom class in which I associate a Cursor (populated with values extracted from a SQLite database) to an AutoCompleteTextView , with an ArrayAdapter . 我正在创建一个自定义类,在其中使用ArrayAdapterCursor (填充有从SQLite数据库提取的值)与AutoCompleteTextView关联。 Each record extracted from Cursor is represented by an ID and a value , and it's added to an ArrayAdapter by value. 从Cursor提取的每个记录都由一个ID和一个value表示,并按添加到ArrayAdapter中。 While adding values, I also create two ArrayList to keep track of both IDs and values. 在添加值时,我还创建了两个ArrayList来跟踪ID和值。

I'd like to be able to get selected item position , but I actually cannot do it, even with onItemClick Listener. 我希望能够获得所选项目的位置 ,但是实际上,即使使用onItemClick Listener,我也无法做到这一点。

Here it is some code from my custom class: 这是我的自定义类中的一些代码:

private AutoCompleteTextView field;
private String column;
private Activity activity;
private ArrayList<String> list_id, list_values;

//Constructor
public PopulateAutoComplete(int elementFromLayout, String column, Activity activity) {
    this.field = (AutoCompleteTextView) activity.findViewById(elementFromLayout);
    this.activity = activity;
    this.column = column;
}
//Reset two lists associated to actual element
private void initializeLists() {
    list_id= new ArrayList<>();
    list_values= new ArrayList<>();
}
//Populating methods
public void populate(Cursor cursor_total, String column_id, String column_values) {
    initializeLists();
    int i=0;
    String id = null;
    String value = null;
    cursor_total.moveToFirst();
    do {
        id = cursor_total.getString(cursor_total.getColumnIndex(column_id));
        value = cursor_total.getString(cursor_total.getColumnIndex(column_values));
        list_id.add(i,id);
        list_values.add(i,value);
        i++;
    } while (cursor_total.moveToNext());
    adapter = new ArrayAdapter<>(activity,android.R.layout.simple_dropdown_item_1line, list_values);
    field.setAdapter(adapter);
}
//Method which select the right item from the list
public void selectValue(Cursor cursor_single, String column_value_to_select) {
    String id_to_verify = cursor_single.getString(cursor_single.getColumnIndex(column_value_to_select);
    loop: {
        for (int i=0; i<listaID.size(); i++) {
            if (list_id.get(i).equals(id_to_verify)) {
                adapter.getItem(i);
                field.setText(list_values.get(i));
                break loop;
            }
        }
    }
    setListener();
}
private void setListener() {
    field.setOnItemClickListener(listener);
}
private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //How to get ID of selected item here?
    }
};

And here it's the code from my MainActivity : 这是我MainActivity中的代码:

PopulateAutoComplete element = new PopulateAutoComplete(R.id.element, "column", this);
element.populate(cursor,"id","name");
element.selectValue(cursor_single,"id");

I'd like to have the ID of selected item, so I can use list_id.getItem(position) . 我想要选定项目的ID,因此可以使用list_id.getItem(position)

I tried with field.getListSelection() , list_id.indexOf(adapterView.getSelectedItem()) but it was not helpful. 我尝试使用field.getListSelection()list_id.indexOf(adapterView.getSelectedItem()),但是它没有帮助。 I also know that some of this method are related to actual dropdown list, but I need a method which extract the exact position of an item in the ArrayAdapter; 我也知道某些方法与实际的下拉列表有关,但是我需要一种方法来提取项目在ArrayAdapter中的确切位置。 in this way, I can automatically extract ID and values (note: values are not unique). 这样,我可以自动提取ID和值(注意:值不是唯一的)。

EDIT #1: 编辑#1:

public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        adapterView.getSelectedItemPosition();   //It returns "-1"
        i;  //It returns a result depending on actual shown dropdown list. If I have a list of 200 item and I have 1 item shown on the dropdown, position will be always 0
    }
};

This is my final solution . 这是我的最终解决方案 Thanks pskink for your support. 感谢pskink的支持。

Methods for AutoCompleteTextView custom class: AutoCompleteTextView自定义类的方法:

//1) Insert all the elements into the AutoCompleteTextView
public void populate(String tag, String column_shown) {
    this.TAG = tag;  //I use a tag in order to differentiate queries I need to execute
    this.column_value =column_shown;
    String[] from = {column_shown};
    int[] to = {android.R.id.text1};
    cursorAdapter = new SimpleCursorAdapter(activity, android.R.layout.simple_dropdown_item_1line, null, from ,to, 0);
    setSearchFilter();
    cursorAdapter.setStringConversionColumn(1);
    field.setAdapter(cursorAdapter);
}
//2) Specify which query to use during the auto-complete step (while typing)
private void setSearchFilter() {
    FilterQueryProvider provider = new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence constraint) {
            System.out.println("PAC - runQuery: " + constraint);
            if (TextUtils.isEmpty(constraint)) {
                return null;
            }
            String[] params = {"%" + constraint.toString() + "%"};
            //Different queries for different tags
            switch (TAG) {
                case ("report"): {
                    Cursor c = db.getReport(column_value, params);
                    //db is an istance of a Custom Class for SQLiteDatabase
                    return c;
                }
            }
            return null;
        }
    };
    cursorAdapter.setFilterQueryProvider(provider);
}
//3) Method to select the correct value while loading Activity for the first time. The value is taken from DB
public void selectValue(Cursor c) {
    if (c==null) {
        return;
    }
    if (c.getCount()==0) {
        return;
    }
    String id_to_verify = c.getString(c.getColumnIndex(column_id));
    setID(id_to_verify);  //I need this to take memory of actual record ID
    field.setText(c.getString(c.getColumnIndex(column_value)));  //field is an instance of AutoCompleteTextView custom class
}

Methods for SQLiteDatabase custom class. SQLiteDatabase自定义类的方法。 This was the important part for my issue: I need to specify an _id column inside my query to get methods working. 这是解决我的问题的重要部分:我需要在查询中指定一个_id列,以使方法正常工作。

public Cursor getReport(String column, String params[]) {
    String query = "SELECT id AS _id, name FROM customers WHERE " + column + " LIKE ? ORDER BY name ASC;";
    return db.rawQuery(query,params);
}

Methods for MainActivity : MainActivity方法:

private PopulateAutoComplete customer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    //...
    Cursor cursorCustomer = `...`;  //Used to find actual value on Activity loading
    customer = new PopulateAutoComplete(R.id.customer,"id_customer",db,this);
    customer.populate("report", "name");
    customer.selectValue(cursorCustomer);
}

Try the solution here. 在这里尝试解决方案。 I assume the same value can't appear twice in the data list (for example, you can't have "item1" twice in list_values: 我假设相同的值不能在数据列表中出现两次(例如,您不能在list_values中两次出现“ item1”:

how to find the position of item in a AutoCompletetextview filled with Array 如何在充满数组的AutoCompletetextview中查找项目的位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM