具有自定义对象而不是String对象的MultiAutoCompleteTextView自定义适配器

时间:2014-04-22 12:04:15

标签: android multiautocompletetextview

只有当我将ArrayList<String>传递给适配器时,此代码才能正常工作。但是当我将对象添加到适配器时,在MultiAutoCompleteTextView中它设置对象全名而不是对象全名。我只希望来自JGETDATA对象的first_name。

public class MyAutoComplete extends MultiAutoCompleteTextView implements OnItemClickListener {

    private final String TAG = "ChipsMultiAutoCompleteTextview";



    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message paramAnonymousMessage)
        {
            if (paramAnonymousMessage.what == 0)
            {
                mHandler.removeMessages(0);
                String str = getText().toString().trim();
                Log.e("handler", "yes");

                if (str.length() >= 2) {

                    if(getText().toString().contains(",")) // check comman in string
                    {

                        String chips[] = getText().toString().trim().split(",");

                        Log.e("String", ""+chips[chips.length -1].trim());

                        makeAutoSearchText(chips[chips.length -1].trim());
                    }else{
                        makeAutoSearchText(str);
                    }
                }
            }
        }
    };
    @SuppressLint("NewApi")
    private void makeAutoSearchText(String paramString)
    {

        Log.e("makeAuto", "Yes");

        String[] ids={"search_name"};
        String[] params={paramString};

        GetDataTask getDataTask= new GetDataTask(ids, params);

        getDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    }

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

        private String[] ids;
        private String[] params;
        private JGetDataList jGetDataList;
        private ArrayList<JGetData> updatedList;

        public GetDataTask( String[] ids, String[] params) {
            // TODO Auto-generated constructor stub
            this.ids=ids;
            this.params=params;
        }


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

            String response=Profiles.getDataFromServer(ids, params, "http://stopnswap.com/service/getAllUserlist.php");

            jGetDataList=Profiles.parseAllUserData(response);
            if(jGetDataList != null){
                if(jGetDataList.Success != null){
                    //      adapterList.clear();
                    updatedList= new ArrayList<JGetData>();
                    for(JGetData jGetData : jGetDataList.Success){
                        updatedList.add(jGetData);

                        //      adapterList.add(jGetData);
                        //  Log.e("name",jGetData.name );
                    }
                }else{
                    //  adapterList.clear();
                }
            }


            Log.e("Data", ""+response);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if(updatedList != null){
                ((SearchListAdapter)getAdapter()).setContactList(updatedList);
            }
            //  adapter.notifyDataSetChanged();

        }

    }

    TextWatcher searchViewTextWatch = new TextWatcher()
    {
        public void afterTextChanged(Editable paramAnonymousEditable) {}

        public void beforeTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {}

        public void onTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3)
        {
            String str=null;
            if (paramAnonymousCharSequence != null)
            {
                str = paramAnonymousCharSequence.toString().trim();
                if (str.length() < 2) {
                    //  break label99;
                }
                mHandler.removeMessages(0);
                Message localMessage = Message.obtain(mHandler, 0, str);
                mHandler.sendMessageDelayed(localMessage, 400L);
            }
            while (str.length() >= 1)
            {
                //      HomeSearchForMedicineScreen.this.mImageSearch.setVisibility(8);
                //       HomeSearchForMedicineScreen.this.mImageCross.setVisibility(0);
                return;
                //        label99:
                //      if ((HomeSearchForMedicineScreen.this.mSearchView.getAdapter() instanceof AutoCompleteSearchAdapter)) {
                //        HomeSearchForMedicineScreen.this.mAutoCompleteAdapter.notifyDataSetInvalidated();
                //     }
            }
            //     HomeSearchForMedicineScreen.this.mImageSearch.setVisibility(0);
            //     HomeSearchForMedicineScreen.this.mImageCross.setVisibility(8);
        }
    };




    /* Constructor */
    public MyAutoComplete(Context context) {
        super(context);
        init(context);
    }
    /* Constructor */
    public MyAutoComplete(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    /* Constructor */
    public MyAutoComplete(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }
    /* set listeners for item click and text change */
    public void init(Context context){
        setOnItemClickListener(this);
        addTextChangedListener(searchViewTextWatch);

         this.setThreshold(1);
            this.setTokenizer(new CustomCommaTokenizer());
    }
    /*TextWatcher, If user type any country name and press comma then following code will regenerate chips */
    /*private TextWatcher textWather = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(count >=1){
                if(s.charAt(start) == ',')
                    setChips(); // generate chips
            }
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
        @Override
        public void afterTextChanged(Editable s) {}
    };
     */




    public class CustomCommaTokenizer extends CommaTokenizer{
        @Override
        public CharSequence terminateToken(CharSequence text) {
            CharSequence charSequence = super.terminateToken(text);
            return charSequence.subSequence(0, charSequence.length()-1);
        }
    }

    /*This function has whole logic for chips generate*/
    public void setChips(){
        if(getText().toString().contains(",")) // check comman in string
        {

            SpannableStringBuilder ssb = new SpannableStringBuilder(getText());
            // split string wich comma

            Log.e("Auto", getText().toString().trim());

            String chips[] = getText().toString().trim().split(",");
            int x =0;
            // loop will generate ImageSpan for every country name separated by comma
            for(String c : chips){
                // inflate chips_edittext layout 
                LayoutInflater lf = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
                TextView textView = (TextView) lf.inflate(R.layout.textview, null);
                textView.setText(c); // set text
                //      setFlags(textView, c); // set flag image
                // capture bitmapt of genreated textview
                int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
                textView.measure(spec, spec);
                textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
                Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(),Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(b);
                canvas.translate(-textView.getScrollX(), -textView.getScrollY());
                textView.draw(canvas);
                textView.setDrawingCacheEnabled(true);
                Bitmap cacheBmp = textView.getDrawingCache();
                Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
                textView.destroyDrawingCache();  // destory drawable
                // create bitmap drawable for imagespan
                BitmapDrawable bmpDrawable = new BitmapDrawable(viewBmp);
                bmpDrawable.setBounds(0, 0,bmpDrawable.getIntrinsicWidth(),bmpDrawable.getIntrinsicHeight());
                // create and set imagespan 
                ssb.setSpan(new ImageSpan(bmpDrawable),x ,x + c.length() , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                setMovementMethod(LinkMovementMethod.getInstance());
                ClickableSpan clickSpan = new ClickableSpan() {

                    @Override
                    public void onClick(View view) {
                    //  deleteString();
                    //  Toast.makeText(this, "Hi", Toast.LENGTH_SHORT).show();
                        Log.e("Clic", "cl");

                        deleteString();
                    }

                };
                ssb.setSpan(clickSpan,x, x + c.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                x = x+ c.length() +1;
            }
            // set chips span 
        //  setText(ssb);
            // move cursor to last 
        //  setSelection(getText().toString().length());


            setSpannableText(ssb);
        }


    }
    public void setSpannableText(final Spannable ssb){
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                setText(ssb);
                setSelection(getText().toString().length());


            }
        }, 20);
    }


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


    //  String myString= getText().toString() +"," +((JGetData)parent.getItemAtPosition(position)).first_name;

    //  setText(myString);
        setChips(); // call generate chips when user select any item from auto complete

        //  Contact contact = (Contact) parent.getItemAtPosition(position);
    //  SmsUtil.selectedContact.put(contact.num, contact.contactName);
    //  Compose.selectedContact.put(key, value)



    }


    private void deleteString(){
        int[] startEnd = getSelectionStartAndEnd();
        int i = startEnd[0];
        int j = startEnd[1];
        //isTextDeletedFromTouch = true;
    //  isTextAdditionInProgress = true;

        final SpannableStringBuilder sb = new SpannableStringBuilder(this.getText()
            );


        String deletedSubString = sb.subSequence(Math.min(i, j),
                Math.max(i, j)).toString();
    //  deleteFromHashMap(deletedSubString);

        boolean hasCommaAtLast = true;
        try {
            sb.subSequence(Math.min(i, j + 1), Math.max(i, j + 1))
                    .toString();
        } catch (Exception e) {
            hasCommaAtLast = false;
        }

        sb.replace(Math.min(i, hasCommaAtLast ? j + 1 : j),
                Math.max(i, hasCommaAtLast ? j + 1 : j), "");


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setText(sb);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                    //  isTextAdditionInProgress = false;
                    //  stringLength = CustomMultiAutoCompleteTextView.this.getText().toString().length();
                    //  isTextDeletedFromTouch = false;
                        //Log.i("I am replacing text","I am replacing text 4");
                        setMovementMethod(LinkMovementMethod.getInstance());
                    }
                },50);

            }
        }, 10);
    //    setChips();
    }

    private int[] getSelectionStartAndEnd(){
        int[] startEnd = new int[2];
        startEnd[0] = this.getSelectionStart()<0?0:this.getSelectionStart();
        startEnd[1] = this.getSelectionEnd()<0?0:this.getSelectionEnd();
        return startEnd;
    }
}

我的适配器

public class SearchListAdapter extends ArrayAdapter<JGetData>{



    private Context context;
    private ArrayList<JGetData> list;


    public SearchListAdapter(Context context, ArrayList<JGetData> list) {
        // TODO Auto-generated constructor stub
        super(context,  android.R.layout.simple_dropdown_item_1line,list);
        this.context=context;
        this.list=list;


    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }
    @Override
    public JGetData getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @SuppressWarnings("unchecked")
    public void setContactList(ArrayList<JGetData>list) {
        // this isn't the efficient method
        // need to improvise on this
        this.list = list;
    //  this.cloneContactList = (ArrayList<Contact>) this.contactList.clone();
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        Holder holder;
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.item_search_list, null);
            holder= new Holder();

            holder.Name=(TextView)convertView.findViewById(R.id.item_Search_list_Name);

            convertView.setTag(holder);
        }else{
            holder=(Holder)convertView.getTag();
        }

        holder.Name.setText(""+list.get(position).first_name);

    //  Log.e("Adapter", ""+list.get(position).first_name);


        return convertView;

    }



    private class Holder{


        public TextView Name;


    }



}

1 个答案:

答案 0 :(得分:0)

实现这一目标的正确方法是实现与适配器的Filterable接口。实现方法getFilter()将返回您自己的convertResultToString(Object resultValue)方法的实现。