Android addTextChangedListener与带子文本的listview

Android addTextChangedListener与带子文本的listview,android,listview,android-emulator,textwatcher,Android,Listview,Android Emulator,Textwatcher,我想在列表中搜索并再次在列表中显示结果 所以我使用了addtextchangelistener,但找不到一种方法使它与listview和subtext一起工作 这是我的密码: package com.android; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamRe

我想在列表中搜索并再次在列表中显示结果 所以我使用了addtextchangelistener,但找不到一种方法使它与listview和subtext一起工作

这是我的密码:

  package com.android;

    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.LineNumberReader;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.StringTokenizer;

    import android.app.ListActivity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.util.Log;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;

    public class MyListDemoActivity extends ListActivity {
        /** Called when the activity is first created. */
        TextView tv;



        //** List<String> content;

        EditText actv;
        List<String> arr_sort;
        //** ArrayAdapter<String> adapter;
        SimpleAdapter simpleadapter;
        ListView lv;

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

            String line = " ";

            LineNumberReader linenoreader = null;
            StringTokenizer stringtokanixer = null;
        //**    content = new ArrayList<String>();
            List<Map<String,String>> data= new ArrayList<Map<String,String>>();

            lv = (ListView) findViewById(android.R.id.list);

            try {

                InputStream istream = getResources().openRawResource(R.raw.grelist);
                InputStreamReader streamreader = new InputStreamReader(istream);

                linenoreader = new LineNumberReader(streamreader);
                linenoreader.mark(15);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }// try catch ends here

            Log.v("getting", "working");

            for(int i=0;i<8;i++)
            {
                Map<String,String> datum= new HashMap<String,String>(2);
                try {
                    line = linenoreader.readLine();
                    Log.v("item",line);
                } catch (IOException e) {

                    e.printStackTrace();
                }
                Log.v("getting", line);
                stringtokanixer = new StringTokenizer(line);

                String st = stringtokanixer.nextToken();
                String meaning="";
                while (stringtokanixer.hasMoreTokens()) {
                    meaning +=" " +stringtokanixer.nextToken();

                }// for ends

                // map is used to add word and meaning 
                datum.put("word",st);
                datum.put("meaning",meaning);
                data.add(datum);

                //List<String> is usedto add
        //**        content.add(st);
            }


            simpleadapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[]{"word","meaning"}, new int[]{android.R.id.text1,android.R.id.text2});

            // setListAdapter(adapter);

            lv.setAdapter(simpleadapter);
            tv = (TextView) findViewById(R.id.textView1);

            actv = (EditText) findViewById(R.id.editText1);


            /*  
                actv.addTextChangedListener(new TextWatcher() {
                int len = 0;


                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                        arr_sort = new ArrayList<String>();

                        len = actv.getText().length();

                        for (int i = 0; i < content.size(); i++) {
                            if (len <= content.get(i).length()) {
                                if (actv.getText()
                                        .toString()
                                        .trim()
                                        .equalsIgnoreCase(
                                                (String) content.get(i).subSequence(0,
                                                        len))) {

                                    arr_sort.add(content.get(i));
                                    Log.v("infor loop afterTextChanged", s.toString());
                                }

                            }

                        }

            //          adapter.notifyDataSetChanged();

                        adapter = new ArrayAdapter<String>(MyListDemoActivity.this,
                            android.R.layout.simple_list_item_1, arr_sort);
                        setListAdapter(adapter);
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                        Log.v("beforetextchange","hello here");
                }

                @Override
                public void afterTextChanged(Editable s) {
                    Log.v("aftertextchange","hello here");

                }
            }); // text watcher class ends here
    */


        }// on create ends here

        public void onListItemClick(ListView ls, View v, int position, long id) {
            //tv.setText(content.get(position));

            // tv.setText(content[position]) // in case of string

        }// endsd here onListItemClick(
    }
package.com.android;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.LineNumberReader;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
导入java.util.StringTokenizer;
导入android.app.ListActivity;
导入android.os.Bundle;
导入android.text.Editable;
导入android.text.TextWatcher;
导入android.util.Log;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.EditText;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
公共类MyListDemoActivity扩展了ListActivity{
/**在首次创建活动时调用*/
文本视图电视;
//**列出内容;
编辑文本actv;
列表arr_排序;
//**阵列适配器;
simpledapter simpledapter;
ListView lv;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
字符串行=”;
LineNumberReader linenorreader=null;
StringTokenizer StringTokenixer=null;
//**content=newarraylist();
列表数据=新的ArrayList();
lv=(ListView)findViewById(android.R.id.list);
试一试{
InputStream istream=getResources().openRawResource(R.raw.grelist);
InputStreamReader streamreader=新的InputStreamReader(istream);
LineNorReader=新的LineNumberReader(streamreader);
LinenReader.标记(15);
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}//试着在这里接球
Log.v(“获取”、“工作”);

对于(int i=0;i,以下是我如何更改您的代码以使其正常工作:

1。我将删除
arr\u sort
变量,并添加另一个
ArrayList
Maps
来保存过滤后的值:

//  List<String> arr_sort;
    final ArrayList<Map<String, String>> data = 
        new ArrayList<Map<String, String>>();
    final ArrayList<Map<String, String>> filteredData = 
        new ArrayList<Map<String, String>>();
3.接下来,我将过滤代码从
onTextChanged
方法移动到
extextchanged
方法,以基于输入的整个文本执行过滤。使用Regexp也比所有字符串操作(+,substring…)消耗更少的资源

这样,您的
TextWatcher
实现将如下所示:

actv.addTextChangedListener(new TextWatcher()
{
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {}

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

    @Override
    public void afterTextChanged(Editable s)
    {
        Log.v("MLDA", "afterTextChanged");
        // a temporary source list for better performance:
        // if it's possible, use the smaller filtered list
        final ArrayList<Map<String, String>> tmpSource = 
            new ArrayList<Map<String,String>>();
        tmpSource.addAll(
            (filterText.length() > 0 && s.toString().contains(filterText)) 
            ? filteredData : data);
        filterText = s.toString();

        // a temporary result list to fill with the filtered data
        final ArrayList<Map<String, String>> tmpResult = 
            new ArrayList<Map<String,String>>();

        if (filterText.length() == 0)
            tmpResult.addAll(data); //if no filter, return the base data
        else
        {
            final Pattern pattern = 
                Pattern.compile("(?i)" + Pattern.quote(s.toString()));
            Matcher matcher;
            for (final Map<String, String> map : tmpSource)
            {
                //first match against the "word":
                matcher = pattern.matcher(map.get("word"));
                if (!matcher.find())
                {
                    //if no matches were found, try to match the "meaning"
                    matcher = pattern.matcher(map.get("meaning"));
                    if (!matcher.find())
                        continue; //if no match, move to the next map
                }
                tmpResult.add(map); //match found: add to new list
            }
        }

        filteredData.clear();
        filteredData.addAll(tmpResult);
        simpleadapter.notifyDataSetChanged(); // update display
    }
});
actv.addTextChangedListener(新的TextWatcher()
{
@凌驾
public void onTextChanged(字符序列、int start、int before、int count)
{}
@凌驾
更改前文本之前的公共void(字符序列s、int start、int count、int after)
{}
@凌驾
公共无效后文本已更改(可编辑)
{
Log.v(“MLDA”、“后文本更改”);
//用于提高性能的临时源列表:
//如果可能,请使用较小的筛选列表
最终阵列列表tmpSource=
新的ArrayList();
tmpSource.addAll(
(filterText.length()>0和&s.toString().contains(filterText))
?过滤器数据(数据);
filterText=s.toString();
//用筛选数据填充的临时结果列表
最终阵列列表tmpResult=
新的ArrayList();
如果(filterText.length()==0)
tmpResult.addAll(data);//如果没有筛选器,则返回基本数据
其他的
{
最终图案=
Pattern.compile(“(?i)”+Pattern.quote(s.toString());
匹配器匹配器;
用于(最终地图:tmpSource)
{
//与“单词”的第一个匹配:
matcher=pattern.matcher(map.get(“word”);
如果(!matcher.find())
{
//如果未找到匹配项,请尝试匹配“含义”
matcher=pattern.matcher(map.get(“含义”));
如果(!matcher.find())
继续;//如果不匹配,则移动到下一个映射
}
tmpResult.add(map);//找到匹配项:添加到新列表
}
}
filteredData.clear();
filteredData.addAll(tmpResult);
simpleadapter.notifyDataSetChanged();//更新显示
}
});
使用临时列表可以在不进行gui更新的情况下构建整个筛选数据(如果直接将项目删除/添加到
filteredData
列表中,适配器将触发更新方法)

还要注意,通过检查新的过滤器文本是否包含旧的过滤器文本,我们可以使用当前的
filteredData
列表作为源

类似地,如果
filterText
是一个空字符串,那么执行任何匹配都没有意义,我们只需返回
base
列表即可;
ArrayList<String> tempList ;
edtText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (!edtText.getText().toString().equalsIgnoreCase("")){
                    tempList = new ArrayList<String>();
                    tempList.clear();
                    String text = filterText.getText().toString();
                    for(int i=0 ;i< listname.size();i++){
                        //if(globalconstant.mosq_list.get(globalconstant.hashformosq.get(globalconstant.tempList.get(i))).name.toUpperCase().toString().contains(text.toUpperCase())){
                        if(listname.get(i).toUpperCase().toString().contains(text.toUpperCase())){
                            tempList.add(listname.get(i));
                        }
                    }
                 used changed tempList
                }else{

                    unchaged tempList
                }
            }
        });
    }
addTextChangedListener(新的TextWatcher(){ @凌驾 public void onTextChanged(字符序列、int start、int before、int count){ //TODO自动生成的方法存根 } @凌驾 更改前的公共无效(字符序列、整数开始、整数计数、, 整数后){ //TODO自动生成的方法存根 } @凌驾 公共无效后文本已更改(可编辑){ //TODO自动生成的方法存根 if(!edtText.getText().toString().equalsIgnoreCase(“”){ 圣殿骑士
ArrayList<String> tempList ;
edtText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (!edtText.getText().toString().equalsIgnoreCase("")){
                    tempList = new ArrayList<String>();
                    tempList.clear();
                    String text = filterText.getText().toString();
                    for(int i=0 ;i< listname.size();i++){
                        //if(globalconstant.mosq_list.get(globalconstant.hashformosq.get(globalconstant.tempList.get(i))).name.toUpperCase().toString().contains(text.toUpperCase())){
                        if(listname.get(i).toUpperCase().toString().contains(text.toUpperCase())){
                            tempList.add(listname.get(i));
                        }
                    }
                 used changed tempList
                }else{

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

    <EditText android:id="@+id/search" android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:inputType="text" />

    <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" />

</LinearLayout>
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ListViewSearchActivity extends Activity implements TextWatcher {

    private SimpleAdapter simpleAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        EditText search = (EditText) findViewById(R.id.search);
        search.addTextChangedListener(this);

        List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        for(int i=0;i<8;i++) {
            Map<String,String> map = new HashMap<String, String>(2);
            map.put("word", "word " + i);
            map.put("meaning", "meaning " + (i + 10));
            data.add(map);
        }

        ListView listView = (ListView) findViewById(R.id.list);
        this.simpleAdapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[]{"word","meaning"}, new int[]{android.R.id.text1,android.R.id.text2});
        listView.setAdapter(this.simpleAdapter);
    }

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

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        this.simpleAdapter.getFilter().filter(s.toString());
    }

}