如何动态地添加建议用preserving人物状态,以autocompletetextview连同照片 [英] How to dynamically add suggestions to autocompletetextview with preserving character status along with images

查看:164
本文介绍了如何动态地添加建议用preserving人物状态,以autocompletetextview连同照片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我使用code给文本建议。我想补充的另一个文本和图像。我怎么做?目前,我使用的是code below.I显示文本,但不显示图像。如何做我设置了形象呢?

 公共类AutoCompleteTextViewActivity延伸活动{

ImageLoader的ImageLoader的;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);

        DisplayImageOptions defaultOptions =新DisplayImageOptions.Builder()
        .cacheInMemory(真)
        .cacheOnDisc(真)
        。建立();

ImageLoaderConfiguration配置=新ImageLoaderConfiguration.Builder(getApplicationContext())
        .defaultDisplayImageOptions(defaultOptions)
        。建立();
。ImageLoader.getInstance()的init(配置);


        AutoCompleteTextView ACTV =新AutoCompleteTextView(本);
        actv.setThreshold(1);
        最终的String []从= {BaseColumns._ID,姓名,艺术家,标题};
        INT []到= {R.id.list_image,R.id.textView1,R.id.textView2,R.id.textView3};
        最后SimpleCursorAdapter适配器=新SimpleCursorAdapter(这一点,R.layout.list_row,空,从,到);
        adapter.setStringConversionColumn(1);
        ViewBinder viewBinder =新ViewBinder(){
             公共布尔setViewValue(查看视图,光标指针,整数参数:columnIndex){
                 如果(参数:columnIndex == 0){
                     ImageView的IV =(ImageView的)观点;
                     。点阵位图= cursor.getExtras()getParcelable(图像);
                     如果(位图!= NULL){
                         iv.setImageBitmap(位);
                     }
                     返回true;
                 }
                 返回false;
             }
        };
        adapter.setViewBinder(viewBinder);
        FilterQueryProvider提供商=新FilterQueryProvider(){
            ExecutorService的mpool上= Executors.newCachedThreadPool();
            乌里URI = Uri.parse(适配器://自动完成);

            公共光标runQuery(CharSequence的约束){
                如果(约束== NULL){
                    返回null;
                }
                尝试 {
                    返回callWebService(约束,从);
                }赶上(JSONException E){
                    e.printStackTrace();
                    返回null;
                }
            }

            //在这里做的Web请求
            私人光标callWebService(CharSequence的约束的String [] columnNames)抛出JSONException {
                Log.d(TAG,callWebService为:+约束);
                MatrixCursor光标=新MyMatrixCursor(columnNames);

                // TODO做真正的网络请求
                //调用的Web服务,在这里,并保持结果jsonStr

            //字符串A =约束;
                的JSONObject json=JSONfunctions.getJSONfromURL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+约束+&放大器; API_KEY = 63692beaaf8ba794a541bca291234cd3和放大器;格式= JSON);



                JSONObject的JS1 = json.getJSONObject(艺术家);
                JSONObject的JS = js1.getJSONObject(相似);
                JSONArray resultArray = js.getJSONArray(艺术家);


                INT长度= resultArray.length();
                的for(int i = 0; I<长度;我++){
                    字符串数据= resultArray.getJSONObject(我).getString(姓名);

                    字符串dataimage = resultArray.getJSONObject(我).getJSONArray(图像)getJSONObject(我).getString(#文本)。

                    cursor.newRow()。加(I)
                        。新增(数据)
                        。新增(数据)
                        。新增(数据);

                    字符串link = dataimage;
                    //获取基于链接缓存包(使用HashMap的<字符串,包>)
                    //如果新的链路发起异步请求得到位图

                    // TODO实现HashMap的缓存

                    //新的异步请求
                    捆绑额外=新包();
                    尝试 {
                        mPool.submit(新ImageRequest(链接,临时演员));
                    }赶上(MalformedURLException异常E){
                        e.printStackTrace();
                    }
                    cursor.respond(临时演员);
                }
                cursor.setNotificationUri(getContentResolver(),URI);
                返回游标;
            }

            类ImageRequest实现Runnable {
                私人网址mUrl;
                私人捆绑mExtra;

                公共ImageRequest(字符串连接,捆绑多余的)抛出MalformedURLException的{
                    mUrl =新的URL(链接);
                    mExtra =多余的;
                }

                公共无效的run(){
                            字符串变量=登陆;
                            // TODO做真正的网络请求
                            //模拟网络延迟
// Log.d(TAG,让+ mUrl);
//                          尝试 {
//视频下载(2000 +(长)(4000 *的Math.random()));
//}赶上(InterruptedException异常E){
// e.printStackTrace();
//}

                            位图B = imageLoader.loadImageSync(mUrl.toString());
                         //位图B = BitmapFactory.de codeResource(getResources(),mUrl.toString());
                            mExtra.putParcelable(形象,B);
                            getContentResolver()有NotifyChange(URI,空)。
                            Log.d(TAG,跑了一个位图+ b.getWidth()+X+ b.getHeight());

                }


            }
        };
        adapter.setFilterQueryProvider(供应商);
        actv.setAdapter(适配器);



        的LayoutParams PARAMS =新的LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        的setContentView(ACTV,则params);
    }

}
 

///////////////

MyMatrixCursor //////////

 公共类MyMatrixCursor扩展MatrixCursor {
    名单<包> mBundles =新的ArrayList<包>();

    公共MyMatrixCursor(的String [] columnNames){
        超(columnNames);
    }

    @覆盖
    公共捆绑响应(捆绑演员){
        mBundles.add(临时演员);
        返回临时演员;
    }

    @覆盖
    公共捆绑getExtras(){
        返回mBundles.get(MPOS);
    }
}
 

////////

JSONfunctions ///////

 公共类JSONfunctions {

    公共静态的JSONObject getJSONfromURL(字符串URL){
        InputStream的是= NULL;
        字符串结果=;
        JSONObject的jArray = NULL;

        // HTTP POST
        尝试{
                HttpClient的HttpClient的=新DefaultHttpClient();
                HttpPost httppost =新HttpPost(URL);
                HTT presponse响应= httpclient.execute(httppost);
                HttpEntity实体= response.getEntity();
                是= entity.getContent();

        }赶上(例外五){
                Log.e(log_tag,错误的HTTP连接+ e.toString());
        }

      //转换响应串
        尝试{
                的BufferedReader读卡器=新的BufferedReader(新InputStreamReader的(就是,ISO-8859-1),8);
                StringBuilder的SB =新的StringBuilder();
                串线= NULL;
                而((行= reader.readLine())!= NULL){
                        sb.append(行+\ N);
                }
                is.close();
                结果= sb.toString();
        }赶上(例外五){
                Log.w(log_tag,错误转换结果+ e.toString());
        }

        尝试{

            jArray =新的JSONObject的(结果);
        }赶上(JSONException E){
                Log.w(log_tag,错误分析数据+ e.toString());
        }

        返回jArray;
    }
}
 

////////

main.xml中 ///

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    机器人:方向=垂直>

    <的TextView
        机器人:ID =@ + ID / textView1
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=选择艺术家
        机器人:textAppearance =:/>中的Andr​​oid ATTR / textAppearanceLarge?

    < AutoCompleteTextView
        机器人:ID =@ + ID / ACTV
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:completionThreshold =1> <不是requestFocus />
    < / AutoCompleteTextView>
    <的TextView
        机器人:ID =@ + ID /选择
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT

        机器人:textAppearance =:/>中的Andr​​oid ATTR / textAppearanceLarge?

< / LinearLayout中>
 

/////

list_row.xml ///

 < XML版本=1.0编码=UTF-8&GT?;
< RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:背景=@机器人:彩色/白
    机器人:方向=横向
    机器人:填充=5dip>

    <! -  ListRow左SIED缩略图 - >
    <的LinearLayout机器人:ID =@ + ID /缩略图
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:填充=3dip
        机器人:layout_alignParentLeft =真
        机器人:layout_marginRight =5dip>

        < ImageView的
            机器人:ID =@ + ID / list_image
        机器人:layout_width =WRAP_CONTENT
  机器人:layout_height =WRAP_CONTENT
  机器人:adjustViewBounds =真
  机器人:=了maxWidth42dp
  机器人:=了maxHeight42dp
  机器人:SRC =@可绘制/ ic_launcher
  机器人:scaleType =fitCenter
  机器人:layout_marginLeft =3DP/>

    < / LinearLayout中>

    <! - 标题歌曲 - >
    <的TextView
        机器人:ID =@ + ID / textView1
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignTop =@ + ID /缩略图
        机器人:layout_toRightOf =@ + ID /缩略图
        机器人:文本=测试
        机器人:文字颜色=#040404
        机器人:字体=SANS
        机器人:TEXTSIZE =15dip
        机器人:TEXTSTYLE =黑体/>

    <! - 艺人名称 - >

    <! -  Rightend时间 - >

     <! -  Rightend箭 - >



    <的TextView
        机器人:ID =@ + ID / textView2
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignLeft =@ + ID / textView1
        机器人:layout_centerVertical =真
        机器人:文本=测试
        机器人:文字颜色=#040404
        机器人:TEXTSIZE =5dip
        机器人:TEXTSTYLE =黑体
        机器人:字体=SANS/>

    <的TextView
        机器人:ID =@ + ID / textView3
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignBottom =@ + ID /缩略图
        机器人:layout_toRightOf =@ + ID /缩略图
        机器人:文本=测试
        机器人:文字颜色=#040404
        机器人:TEXTSIZE =15dip
        机器人:TEXTSTYLE =黑体
        机器人:字体=SANS/>

< / RelativeLayout的>
 

/// 清单

///

 < XML版本=1.0编码=UTF-8&GT?;
<舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.example.example
    安卓版code =1
    机器人:VERSIONNAME =1.0>

    <使用-SDK安卓的minSdkVersion =10/>
    <使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>
    <使用-权限的Andr​​oid:名称=android.permission.WRITE_EXTERNAL_STORAG​​E/>

    <应用
        机器人:图标=@可绘制/ ic_launcher
        机器人:标签=@字符串/ APP_NAME>
        <活动
            机器人:标签=@字符串/ APP_NAME
            机器人:名称=AutoCompleteTextViewActivity。>
            <意向滤光器>
                <作用机器人:名称=android.intent.action.MAIN/>

                <类机器人:名称=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;
    < /用途>

< /舱单>
 

解决方案

OK试试这个:

 的LinearLayout LL =新的LinearLayout(本);
    ll.setOrientation(LinearLayout.VERTICAL);

    AutoCompleteTextView ACTV =新AutoCompleteTextView(本);
    actv.setThreshold(1);
    从字符串= {姓名} [];
    INT []到= {android.R.id.text1};
    SimpleCursorAdapter适配器=新SimpleCursorAdapter(这一点,android.R.layout.simple_dropdown_item_1line,空,从,到){

        //需要跨区数据
        @覆盖
        公共无效bindView(查看视图,上下文的背景下,光标光标){
            MyCursor C =(MyCursor)光标;
            TextView的电视=(TextView的)观点;
            tv.setText(c.getSpanned());
        }

        //需要跨区数据
        @覆盖
        公众的CharSequence convertToString(光标指针){
            MyCursor C =(MyCursor)光标;
            返回c.getSpanned();
        }
    };
    FilterQueryProvider提供商=新FilterQueryProvider(){
        @覆盖
        公共光标runQuery(CharSequence的约束){
            如果(约束== NULL){
                返回null;
            }
            MyCursor C =新MyCursor();
            //伪造的Web服务响应
            名单<字符串>名称= callFak​​eWebService(约束);
            INT I = 0;
            对于(字符串名称:名){
                SpannableStringBuilder SSB =新SpannableStringBuilder(名称);
                INT开始= name.indexOf();
                ForegroundColorSpan什么=新ForegroundColorSpan(为0xffff0000);
                ssb.setSpan(什么,开始+ 1,ssb.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                c.newRow()加(我+ +)增加(名称)。;
                c.addSpanned(SSB);
            }
            返回℃;
        }

        //假冒的Web服务请求
        私人列表<字符串> callFak​​eWebService(CharSequence的约束){
            Log.d(TAG,callFak​​eWebService为:+约束);
            的String [] namesArr = {
                    马克·史密斯,
                    莫妮卡·汤普森
                    约翰·怀特,
                    珍妮·布朗
            };
            。串stringConstraint = constraint.toString()与toLowerCase();
            名单<字符串>名称=新的ArrayList<字符串>();
            的for(int i = 0; I< namesArr.length;我++){
                字符串名称= namesArr [I]
                如果(name.toLowerCase()。startsWith(stringConstraint)){
                    names.add(名称);
                }
            }
            返回名称;
        }
    };
    adapter.setFilterQueryProvider(供应商);
    actv.setAdapter(适配器);
    ll.addView(ACTV);
    TextView的电视=新的TextView(本);
    tv.setTextSize(32);
    tv.setTextColor(为0xffff0000);
    tv.setText(类型之一:\ N标志,\ñ莫妮卡\ñ约翰\ñ简);
    ll.addView(电视);
    的setContentView(Ⅱ);
 

在这里定义光标看起来是这样的(它是简约版本只有一个支持跨区一排):

 静态类MyCursor扩展MatrixCursor {
    私有静态最后的String []名字= {BaseColumns._ID,姓名};
    私人的ArrayList<跨区> mSpannedList;

    公共MyCursor(){
        超(名称);
        mSpannedList =新的ArrayList<跨区>();
    }

    公共无效addSpanned(跨区S){
        mSpannedList.add(多个);
    }

    公共跨区getSpanned(){
        返回mSpannedList.get(MPOS);
    }
}
 

修改没有跨区文字:

  AutoCompleteTextView ACTV =新AutoCompleteTextView(本);
    actv.setThreshold(1);
    最终的String []从= {BaseColumns._ID,姓名,艺术家,标题};
    INT []到= {R.id.list_image,R.id.textView1,R.id.textView2,R.id.textView3};
    最后SimpleCursorAdapter适配器=新SimpleCursorAdapter(这一点,R.layout.list_row,空,从,到);
    adapter.setStringConversionColumn(1);
    ViewBinder viewBinder =新ViewBinder(){
         公共布尔setViewValue(查看视图,光标指针,整数参数:columnIndex){
             如果(参数:columnIndex == 0){
                 ImageView的IV =(ImageView的)观点;
                 。点阵位图= cursor.getExtras()getParcelable(图像);
                 如果(位图!= NULL){
                     iv.setImageBitmap(位);
                 }
                 返回true;
             }
             返回false;
         }
    };
    adapter.setViewBinder(viewBinder);
    FilterQueryProvider提供商=新FilterQueryProvider(){
        ExecutorService的mpool上= Executors.newCachedThreadPool();
        乌里URI = Uri.parse(适配器://自动完成);

        公共光标runQuery(CharSequence的约束){
            如果(约束== NULL){
                返回null;
            }
            尝试 {
                返回callWebService(约束,从);
            }赶上(JSONException E){
                e.printStackTrace();
                返回null;
            }
        }

        //在这里做的Web请求
        私人光标callWebService(CharSequence的约束的String [] columnNames)抛出JSONException {
            Log.d(TAG,callWebService为:+约束);
            MatrixCursor光标=新MyMatrixCursor(columnNames);

            // TODO做真正的网络请求
            //调用的Web服务,在这里,并保持结果jsonStr
            串jsonStr ={\ResultArray \:[{\数据\:{\SNO \:\sno1 \\日期\:\2011-08-21十四时27分09秒\,\用户\:\1 \,\链接\:\http://scm-l3.technorati.com/11/11/17/56749/google-docs-revision.jpg ?T = 20111117074048 \,\名字\:\AA \}},{\数据\:{\SNO \:\的SnO2 \,\日期\:\2011 -08-21 14:28:09 \,\用户\:\2 \,\链接\:\http://kcclaveria.com/wp-content/uploads/2013/02/谷歌 - 熊猫penguin.jpg \,\名字\:\降B \}}]};

            JSONObject的JSON =新的JSONObject(jsonStr);
            JSONArray resultArray = json.getJSONArray(ResultArray);

            INT长度= resultArray.length();
            的for(int i = 0; I<长度;我++){
                JSONObject的数据= resultArray.getJSONObject(我).getJSONObject(数据);

                cursor.newRow()。加(I)
                    。新增(data.getString(名字))
                    。新增(data.getString(用户))
                    。新增(data.getString(SNO));

                字符串link = data.getString(链接);
                //获取基于链接缓存包(使用HashMap的<字符串,包>)
                //如果新的链路发起异步请求得到位图

                // TODO实现HashMap的缓存

                //新的异步请求
                捆绑额外=新包();
                尝试 {
                    mPool.submit(新ImageRequest(链接,临时演员));
                }赶上(MalformedURLException异常E){
                    e.printStackTrace();
                }
                cursor.respond(临时演员);
            }
            cursor.setNotificationUri(getContentResolver(),URI);
            返回游标;
        }

        类ImageRequest实现Runnable {
            私人网址mUrl;
            私人捆绑mExtra;

            公共ImageRequest(字符串连接,捆绑多余的)抛出MalformedURLException的{
                mUrl =新的URL(链接);
                mExtra =多余的;
            }

            @覆盖
            公共无效的run(){
                // TODO做真正的网络请求
                //模拟网络延迟
                Log.d(TAG,让+ mUrl);
                尝试 {
                    视频下载(2000 +(长)(4000 *的Math.random()));
                }赶上(InterruptedException异常E){
                    e.printStackTrace();
                }
                位图B = BitmapFactory.de codeResource(getResources(),R.drawable.ic_launcher);
                mExtra.putParcelable(形象,B);
                getContentResolver()有NotifyChange(URI,空)。
                Log.d(TAG,跑了一个位图+ b.getWidth()+X+ b.getHeight());
            }
        }
    };
    adapter.setFilterQueryProvider(供应商);
    actv.setAdapter(适配器);

    的LayoutParams PARAMS =新的LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
    的setContentView(ACTV,则params);
 

和自定​​义MatrixCursor:

 类MyMatrixCursor扩展MatrixCursor {
    名单<包> mBundles =新的ArrayList<包>();

    公共MyMatrixCursor(的String [] columnNames){
        超(columnNames);
    }

    @覆盖
    公共捆绑响应(捆绑演员){
        mBundles.add(临时演员);
        返回临时演员;
    }

    @覆盖
    公共捆绑getExtras(){
        返回mBundles.get(MPOS);
    }
}
 

Currently I am using code to give text suggestion. I would like to add another text and image. How do I do that? Currently, I am using the code below.I shows text but image is not displayed .How do I set the image ?

public class AutoCompleteTextViewActivity extends Activity{

ImageLoader imageLoader;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
        .cacheInMemory(true)
        .cacheOnDisc(true)
        .build();

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
        .defaultDisplayImageOptions(defaultOptions)
        .build();
ImageLoader.getInstance().init(config);


        AutoCompleteTextView actv = new AutoCompleteTextView(this);
        actv.setThreshold(1);
        final String[] from = {BaseColumns._ID, "name", "artist", "title"};
        int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
        final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
        adapter.setStringConversionColumn(1);
        ViewBinder viewBinder = new ViewBinder() {
             public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
                 if (columnIndex == 0) {
                     ImageView iv = (ImageView) view;
                     Bitmap bitmap = cursor.getExtras().getParcelable("image");
                     if (bitmap != null) {
                         iv.setImageBitmap(bitmap);
                     }
                     return true;
                 }
                 return false;
             }
        };
        adapter.setViewBinder(viewBinder);
        FilterQueryProvider provider = new FilterQueryProvider() {
            ExecutorService mPool = Executors.newCachedThreadPool();
            Uri URI = Uri.parse("adapter://autocomplete");

            public Cursor runQuery(CharSequence constraint) {
                if (constraint == null) {
                    return null;
                }
                try {
                    return callWebService(constraint, from);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            // here you make the web request
            private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
                Log.d("TAG", "callWebService for: " + constraint);
                MatrixCursor cursor = new MyMatrixCursor(columnNames);

                // TODO do real network request
                // call web service here and keep the result in "jsonStr" 

            //  String a=constraint;
                JSONObject json=JSONfunctions.getJSONfromURL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+ constraint +"&api_key=63692beaaf8ba794a541bca291234cd3&format=json");



                JSONObject js1=json.getJSONObject("artist");
                JSONObject js=js1.getJSONObject("similar");
                JSONArray resultArray = js.getJSONArray("artist");


                int length = resultArray.length();
                for (int i = 0; i < length; i++) {
                    String data = resultArray.getJSONObject(i).getString("name");

                    String dataimage = resultArray.getJSONObject(i).getJSONArray("image").getJSONObject(i).getString("#text");

                    cursor.newRow().add(i)
                        .add(data)
                        .add(data)
                        .add(data);

                    String link = dataimage;
                    // get cached Bundle based on "link" (use HashMap<String, Bundle>)
                    // or if new link initiate async request for getting the bitmap

                    // TODO implement HashMap caching

                    // new async request
                    Bundle extras = new Bundle();
                    try {
                        mPool.submit(new ImageRequest(link, extras));
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                    cursor.respond(extras);
                }
                cursor.setNotificationUri(getContentResolver(), URI);
                return cursor;
            }

            class ImageRequest implements Runnable {
                private URL mUrl;
                private Bundle mExtra;

                public ImageRequest(String link, Bundle extra) throws MalformedURLException {
                    mUrl = new URL(link);
                    mExtra = extra;
                }

                public void run() {
                            String TAG="log";
                            // TODO do real network request
                            // simulate network delay
//                          Log.d(TAG, "getting " + mUrl);
//                          try {
//                              Thread.sleep(2000 + (long) (4000 * Math.random()));
//                          } catch (InterruptedException e) {
//                              e.printStackTrace();
//                          }

                            Bitmap b = imageLoader.loadImageSync(mUrl.toString());
                         //   Bitmap b = BitmapFactory.decodeResource(getResources(), mUrl.toString());
                            mExtra.putParcelable("image", b);
                            getContentResolver().notifyChange(URI, null);
                            Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());

                }


            }
        };
        adapter.setFilterQueryProvider(provider);
        actv.setAdapter(adapter);



        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        setContentView(actv, params);
    }

}

///////////////

MyMatrixCursor //////////

public class MyMatrixCursor extends MatrixCursor {
    List<Bundle> mBundles = new ArrayList<Bundle>();

    public MyMatrixCursor(String[] columnNames) {
        super(columnNames);
    }

    @Override
    public Bundle respond(Bundle extras) {
        mBundles.add(extras);
        return extras;
    }

    @Override
    public Bundle getExtras() {
        return mBundles.get(mPos);
    }
}

////////

JSONfunctions ///////

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

      //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
        }catch(Exception e){
                Log.w("log_tag", "Error converting result "+e.toString());
        }

        try{

            jArray = new JSONObject(result);            
        }catch(JSONException e){
                Log.w("log_tag", "Error parsing data "+e.toString());
        }

        return jArray;
    }
}

////////

main.xml ///

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick Artist"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <AutoCompleteTextView
        android:id="@+id/actv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"> <requestFocus />
    </AutoCompleteTextView>
    <TextView
        android:id="@+id/selection"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

/////

list_row.xml ///

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="horizontal"
    android:padding="5dip" >

    <!--  ListRow Left sied Thumbnail image -->
    <LinearLayout android:id="@+id/thumbnail" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="3dip"      
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip">

        <ImageView     
            android:id="@+id/list_image"   
        android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:src="@drawable/ic_launcher"
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"/>

    </LinearLayout>

    <!-- Title Of Song-->
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="test"
        android:textColor="#040404"
        android:typeface="sans" 
        android:textSize="15dip"
        android:textStyle="bold"/>

    <!-- Artist Name -->

    <!-- Rightend Duration -->

     <!-- Rightend Arrow -->



    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_centerVertical="true"
        android:text="test"
        android:textColor="#040404"
        android:textSize="5dip"
        android:textStyle="bold"
        android:typeface="sans" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="test"
        android:textColor="#040404"
        android:textSize="15dip"
        android:textStyle="bold"
        android:typeface="sans" />

</RelativeLayout>

/// Manifest

///

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AutoCompleteTextViewActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

解决方案

ok try this:

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    AutoCompleteTextView actv = new AutoCompleteTextView(this);
    actv.setThreshold(1);
    String[] from = {"name"};
    int[] to = {android.R.id.text1};
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to) {

        // required for Spanned data
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            MyCursor c = (MyCursor) cursor;
            TextView tv = (TextView) view;
            tv.setText(c.getSpanned());
        }

        // required for Spanned data
        @Override
        public CharSequence convertToString(Cursor cursor) {
            MyCursor c = (MyCursor) cursor;
            return c.getSpanned();
        }
    };
    FilterQueryProvider provider = new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence constraint) {
            if (constraint == null) {
                return null;
            }
            MyCursor c = new MyCursor();
            // fake web service responses
            List<String> names = callFakeWebService(constraint);
            int i = 0;
            for (String name: names) {
                SpannableStringBuilder ssb = new SpannableStringBuilder(name);
                int start = name.indexOf(" ");
                ForegroundColorSpan what = new ForegroundColorSpan(0xffff0000);
                ssb.setSpan(what, start + 1, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                c.newRow().add(i++).add(name);
                c.addSpanned(ssb);
            }
            return c;
        }

        // fake web service request
        private List<String> callFakeWebService(CharSequence constraint) {
            Log.d(TAG, "callFakeWebService for: " + constraint);
            String[] namesArr = {
                    "Mark Smith",
                    "Monica Thompson",
                    "John White",
                    "Jane Brown"
            };
            String stringConstraint = constraint.toString().toLowerCase();
            List<String> names = new ArrayList<String>();
            for (int i = 0; i < namesArr.length; i++) {
                String name = namesArr[i];
                if (name.toLowerCase().startsWith(stringConstraint)) {
                    names.add(name);
                }
            }
            return names;
        }
    };
    adapter.setFilterQueryProvider(provider);
    actv.setAdapter(adapter);
    ll.addView(actv);
    TextView tv = new TextView(this);
    tv.setTextSize(32);
    tv.setTextColor(0xffff0000);
    tv.setText("type one of:\n  mark,\n  monica,\n  john\n  jane");
    ll.addView(tv);
    setContentView(ll);

where custom Cursor could look like this (it is minimalistic version supporting only one Spanned in a row):

static class MyCursor extends MatrixCursor {
    private static final String[] NAMES = {BaseColumns._ID, "name"};
    private ArrayList<Spanned> mSpannedList;

    public MyCursor() {
        super(NAMES);
        mSpannedList = new ArrayList<Spanned>();
    }

    public void addSpanned(Spanned s) {
        mSpannedList.add(s);
    }

    public Spanned getSpanned() {
        return mSpannedList.get(mPos);
    }
}

EDIT with no Spanned text:

    AutoCompleteTextView actv = new AutoCompleteTextView(this);
    actv.setThreshold(1);
    final String[] from = {BaseColumns._ID, "name", "artist", "title"};
    int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
    final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
    adapter.setStringConversionColumn(1);
    ViewBinder viewBinder = new ViewBinder() {
         public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
             if (columnIndex == 0) {
                 ImageView iv = (ImageView) view;
                 Bitmap bitmap = cursor.getExtras().getParcelable("image");
                 if (bitmap != null) {
                     iv.setImageBitmap(bitmap);
                 }
                 return true;
             }
             return false;
         }
    };
    adapter.setViewBinder(viewBinder);
    FilterQueryProvider provider = new FilterQueryProvider() {
        ExecutorService mPool = Executors.newCachedThreadPool();
        Uri URI = Uri.parse("adapter://autocomplete");

        public Cursor runQuery(CharSequence constraint) {
            if (constraint == null) {
                return null;
            }
            try {
                return callWebService(constraint, from);
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }
        }

        // here you make the web request
        private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
            Log.d("TAG", "callWebService for: " + constraint);
            MatrixCursor cursor = new MyMatrixCursor(columnNames);

            // TODO do real network request
            // call web service here and keep the result in "jsonStr" 
            String jsonStr =  "{\"ResultArray\":[{\"data\":{ \"sno\":\"sno1\", \"date\":\"2011-08-21 14:27:09\", \"user\":\"1\", \"link\":\"http://scm-l3.technorati.com/11/11/17/56749/google-docs-revision.jpg?t=20111117074048\", \"name\":\"Aa\" }},{\"data\":{ \"sno\":\"sno2\", \"date\":\"2011-08-21 14:28:09\", \"user\":\"2\", \"link\":\"http://kcclaveria.com/wp-content/uploads/2013/02/google-panda-penguin.jpg\", \"name\":\"Bb\" }}]}";

            JSONObject json = new JSONObject(jsonStr);
            JSONArray resultArray = json.getJSONArray("ResultArray");

            int length = resultArray.length();
            for (int i = 0; i < length; i++) {
                JSONObject data = resultArray.getJSONObject(i).getJSONObject("data");

                cursor.newRow().add(i)
                    .add(data.getString("name"))
                    .add(data.getString("user"))
                    .add(data.getString("sno"));

                String link = data.getString("link");
                // get cached Bundle based on "link" (use HashMap<String, Bundle>)
                // or if new link initiate async request for getting the bitmap

                // TODO implement HashMap caching

                // new async request
                Bundle extras = new Bundle();
                try {
                    mPool.submit(new ImageRequest(link, extras));
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                cursor.respond(extras);
            }
            cursor.setNotificationUri(getContentResolver(), URI);
            return cursor;
        }

        class ImageRequest implements Runnable {
            private URL mUrl;
            private Bundle mExtra;

            public ImageRequest(String link, Bundle extra) throws MalformedURLException {
                mUrl = new URL(link);
                mExtra = extra;
            }

            @Override
            public void run() {
                // TODO do real network request
                // simulate network delay
                Log.d(TAG, "getting " + mUrl);
                try {
                    Thread.sleep(2000 + (long) (4000 * Math.random()));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
                mExtra.putParcelable("image", b);
                getContentResolver().notifyChange(URI, null);
                Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
            }
        }
    };
    adapter.setFilterQueryProvider(provider);
    actv.setAdapter(adapter);

    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    setContentView(actv, params);

and the custom MatrixCursor:

class MyMatrixCursor extends MatrixCursor {
    List<Bundle> mBundles = new ArrayList<Bundle>();

    public MyMatrixCursor(String[] columnNames) {
        super(columnNames);
    }

    @Override
    public Bundle respond(Bundle extras) {
        mBundles.add(extras);
        return extras;
    }

    @Override
    public Bundle getExtras() {
        return mBundles.get(mPos);
    }
}

这篇关于如何动态地添加建议用preserving人物状态,以autocompletetextview连同照片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆