有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓中实现自动完成或自动建议?

我已经做了一个自动推荐的演示。我有名称(字符串)和代码(字符串)。我有大约2000个名字和密码。。因此,我采用字符串数组,并将其置于以下格式中name-(code)示例“Alexandra Palace-(AAP)”,。我的问题是,我需要使用代码而不是名称进行过滤。实际上,当我在输入字段中键入时,它与名称匹配,而不是与代码匹配。但我需要用代码过滤

范例 当我输入“lwy”时,它不会显示“MNCRLWY-(lwy)”,您能告诉我如何实现这一点吗

我试着这样做

public class GlobalList {

    public static String[] stationList={

        "MNCRLWY-(LWY)",
        "Lympstone Commando-(LYC)",
        "Lydney-(LYD)",
        "Lye-(LYE)",
        "Lympstone Village-(LYM)",
        "Lymington Pier-(LYP)",
        "Lymington Town-(LYT)",
        "Lazonby & Kirkoswald-(LZB)",
        "Leeds, Whitehall (Bus)-(LZZ)",
        "Macclesfield-(MAC)",
        "Maghull-(MAG)",
        "Maidenhead-(MAI)",
        "Malden Manor-(MAL)",
        "Manchester Piccadilly-(MAN)",
        "Martins Heron-(MAO)",
        "Margate-(MAR)",
        "Manors-(MAS)",
        "Matlock-(MAT)",
        "Mauldeth Road-(MAU)",
        "Mallow-(MAW)",
        "Maxwell Park-(MAX)",
        "Maybole-(MAY)",
        "Millbrook (Hampshire)-(MBK)",
        "Middlesbrough-(MBR)",
        "Moulsecoomb-(MCB)",
        "Metro Centre-(MCE)",
        "March-(MCH)",
        "Marne La Vallee-(MCK)",
        "Morecambe-(MCM)",
        "Machynlleth-(MCN)",
        "Manchester Oxford Road-(MCO)",
        "Manchester Victoria-(MCV)",
        "Maidstone Barracks-(MDB)",
        "Maidstone East-(MDE)",
        "Midgham-(MDG)",
        "Middlewood-(MDL)",
        "Maiden Newton-(MDN)",
        "Morden South-(MDS)",
        "Maidstone West-(MDW)",
        "MAERDY-(MDY)",
        "Meols Cop-(MEC)",
        "Meldreth-(MEL)",
        "Menheniot-(MEN)",
        "Meols-(MEO)",
        "Meopham-(MEP)",
        "Merthyr Tydfil-(MER)",
        "Melton-(MES)",
        "Merthyr Vale-(MEV)",
        "Maesteg (Ewenny Road)-(MEW)",
        "Mexborough-(MEX)",
        "Merryton-(MEY)",
        "Morfa Mawddach-(MFA)",
        "Minffordd-(MFD)",
        "Minffordd-(MFF)",
        "Milford Haven-(MFH)",



};

}

自定义适配器

public class CustomAutocompletAdapter extends BaseAdapter implements Filterable{

    private  String stationNameAndCodeValue ;
    ArrayList<String> autolistArray;
    ArrayList<String> objects;
    private Context context;
    public CustomAutocompletAdapter( Context context, String[] autolistArray){
        this.autolistArray=new ArrayList<String>();
     for(int i=0;i<autolistArray.length;i++){
   this.autolistArray.add(autolistArray[i]);

    }        this.context = context;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return autolistArray.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return autolistArray.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return  position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
         View v = convertView;
            if (v == null) {
                LayoutInflater mInflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = mInflater.inflate(R.layout.custom_row_adapter, null);
            }

            final TextView stationNameAndCode = (TextView) v
                    .findViewById(R.id.item_selectStationName);



            stationNameAndCodeValue = autolistArray.get(position);


            stationNameAndCode.setText(stationNameAndCodeValue);


            return v;
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
        Filter myFilter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                    FilterResults results) {

                System.out.println("Constraint " + constraint);
                Log.d("-----------", "publishResults");
                  if (results.count > 0 && results != null) {
                objects = (ArrayList<String>) results.values;

                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }


            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                   Log.d("-----------", "performFiltering");
            FilterResults results = new FilterResults(); 
            List<String> FilteredArrList = new ArrayList<String>();

            if (objects == null) {
               objects = new ArrayList<String>(autolistArray); // saves

            }


                Locale locale = Locale.getDefault();

                constraint = (String) constraint
                        .toString().toLowerCase(locale);
                if (constraint == null || constraint.length() == 0) {

                    // set the Original result to return
                results.count = objects.size();
                results.values = objects;

                } else {
               for (int i = 0; i < objects.size(); i++) {
                    String name= objects.get(i);


                    String newName = name.substring(name.indexOf('('),name.length()-1);
                    if (newName.toLowerCase(locale).contains(constraint)) 
                    {
                          FilteredArrList.add(name);
                    }
                }
                // set the Filtered result to return
                results.count = FilteredArrList.size();

                results.values = FilteredArrList;

                }
                return results;
            }

            @Override
            public CharSequence convertResultToString(Object resultValue) {
                // TODO Auto-generated method stub
                //convert object to string
                Log.d("-----------", "convertResultToString");
                return "";
            }
        };
        return myFilter;
    }

}

主要活动:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_station);

         autocompleteView = (AutoCompleteTextView) findViewById(R.id.item_autoComplete);

         STATION_LIST = new String[GlobalList.stationList.length
                                            + GlobalExtendStationList.stationList.length];
                                    System.arraycopy(GlobalList.stationList, 0, STATION_LIST, 0,
                                            GlobalList.stationList.length);
                                    System.arraycopy(GlobalExtendStationList.stationList, 0,
                                            STATION_LIST, GlobalList.stationList.length,
                                            GlobalExtendStationList.stationList.length);
                                    autosuggestAdapter = new CustomAutocompletAdapter(this,STATION_LIST);
                                    autocompleteView.setAdapter(autosuggestAdapter);

Xml

<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:orientation="vertical" >

    <LinearLayout
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content" 
        安卓:orientation="horizontal"
        安卓:gravity=""
        >

        <TextView
            安卓:id="@+id/textView1"
            安卓:layout_width="wrap_content"
            安卓:layout_height="wrap_content"
            安卓:text="Choose station"
              安卓:layout_marginLeft="20dp"
            安卓:textAppearance="?安卓:attr/textAppearanceMedium" />

        <AutoCompleteTextView
            安卓:id="@+id/item_autoComplete"
            安卓:layout_width="100dp"
            安卓:layout_height="wrap_content"
            安卓:layout_weight="0.5"
            安卓:ems="10"
            安卓:layout_marginLeft="20dp"
             安卓:layout_marginRight="20dp"
            安卓:text="AutoCompleteTextView" >

            <requestFocus />
        </AutoCompleteTextView>

    </LinearLayout>

</LinearLayout>

共 (1) 个答案

  1. # 1 楼答案

    在检查整个字符串(名称)中的搜索字符串时,如果它在名称中的任何位置找到了插入字符串,则会将其添加到结果中
    所以使用这个

               String newName = name.subString(indexOf('('),name.lastIndexOf(')'));
               if (newName.toLowerCase(locale).contains(constraint)) 
               {
                     FilteredArrList.add(name);
               }
    

    而不是

               if (name.toLowerCase(locale).contains(constraint)) 
               {
                     FilteredArrList.add(name);
               }