在搜索列表视图与搜索文本颜色列表视图中突出 [英] Searching listview with searched textcolor highlighted in Listview

查看:118
本文介绍了在搜索列表视图与搜索文本颜色列表视图中突出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表视图 arrayadapter ..我需要在我的音乐应用程序中实现这...帮助我出去

 公共类Search_Class延伸活动{

        的EditText searchedit;
        ListView控件listview3;
        SongsManager songManager;
        上下文语境;
        的String [] ABC;
        ArrayList的<字符串>名称;
        ArrayList的<字符串> ArrayList的;
        ArrayAdapter<字符串>广告;
        私人的ArrayList< HashMap的<字符串,字符串>> songsList =新的ArrayList< HashMap的<字符串,字符串>>();

        @覆盖
        保护无效的onCreate(包savedInstanceState){
            // TODO自动生成方法存根
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.my_search);
            上下文= getBaseContext();
            sea​​rchedit =(EditText上)findViewById(R.id.searchedit);
            listview3 =(ListView控件)findViewById(R.id.listview3);
            songManager =新SongsManager();
            songsList = songManager.getPlayList(上下文);
            名称=新的ArrayList<字符串>();
            ArrayList的=新的ArrayList<字符串>();

            的for(int i = 0; I< songsList.size();我++){
                HashMap的<字符串,字符串>物镜= songsList.get(ⅰ);

                names.add(obj.get(songTitle));
                arrayList.add(obj.get(songTitle));
            }

            ABC =新的String [names.size()];
            ABC = names.toArray(ABC);

            listview3.setTextFilterEnabled(真正的);

            //广告=新的ArrayAdapter<字符串>(MySearch.this,
            // android.R.layout.simple_list_item_1,ABC);
            // listview3.setAdapter(广告);
            listview3.setOnItemClickListener(新OnItemClickListener(){

                公共无效onItemClick(适配器视图<>母公司视图中查看,
                        INT位置,长的id){
                    //获取列表项指标

                    的String [] ABC1 =新的String [arrayList.size()];
                    ABC1 = arrayList.toArray(ABC);

                    INT songIndex;

                    的for(int i = 0; I< abc1.length;我++){
                        如果(ABC [位置] .equalsIgnoreCase(ABC1 [I])){
                            songIndex =我;
                            意图=新的意图(Search_Class.this,
                                    MainActivity.class);
                            //发送songIndex到PlayerActivity
                            共享preferences SP;
                            SP = getShared preferences(lastplayed,MODE_PRIVATE);
                            编辑器编辑= sp.edit();
                            edit.putBoolean(searchSongIndex,真正的);
                            edit.commit();
                            in.putExtra(songIndex,songIndex);

                            in.putExtra(FLAG,真正的);
                            startActivity(在);
                            完();

                            打破;
                        }
                    }

                }

            });
            // ad.notifyDataSetChanged();

            sea​​rchedit.addTextChangedListener(新TextWatcher(){

                @覆盖
                公共无效onTextChanged(CharSequence的arg0中,诠释ARG1,INT ARG2,
                        INT ARG3){
                    // TODO自动生成方法存根
                    // MySearch.this.ad.getFilter()过滤器(arg0中)。

                    字符串文本= arg0.toString()与toLowerCase(Locale.getDefault())。
                    过滤器(文本);

                }

                @覆盖
                公共无效beforeTextChanged(CharSequence的arg0中,INT ARG1,
                        INT ARG2,诠释ARG3){
                    // TODO自动生成方法存根

                }

                @覆盖
                公共无效afterTextChanged(编辑为arg0){
                    // TODO自动生成方法存根

                }
            });

        }

        公共无效过滤器(字符串charText){
            的System.out.println(文字---+ charText);
            charText = charText.toLowerCase(Locale.getDefault());
            names.clear();
            如果(charText.length()== 0){
                的System.out.println(如果---+ arrayList.size());
                ABC =新的String [arrayList.size()];
                ABC = arrayList.toArray(ABC);

                // names.addAll(ArrayList中);
            } 其他 {
                的System.out.println(其他);

                的for(int i = 0; I< abc.length;我++){

                    的System.out.println(ABC [我] + - + charText);

                    如果(ABC [I] .toLowerCase(Locale.getDefault())。包含(charText)){
                        names.add(ABC [I]);
                    }
                }
                ABC =新的String [names.size()];
                ABC = names.toArray(ABC);
            }
            AD =新的ArrayAdapter<字符串>(Search_Class.this,
                    android.R.layout.simple_list_item_1,ABC);
            listview3.setAdapter(广告);
            ad.notifyDataSetChanged();
        }

        @覆盖
        公共布尔onCreateOptionsMenu(功能菜单){
            // TODO自动生成方法存根
            返回false;
        }

    }

刚刚创建了一个自定义`Listview`使用`ListActivity`

公共类SearchingClass扩展ListActivity {
    的EditText等;
    ListView的LV;
    上下文语境;
    ArrayList的<字符串> AllSongs;
    的String [] AllSongsArray;
    SongsManager songManager;
    私人的ArrayList< HashMap的<字符串,字符串>> songsList =新的ArrayList< HashMap的<字符串,字符串>>();
    SearchClass_Adapter适配器;
    INT长度限制:Textlength = 0;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_searching_class);
        等=(EditText上)findViewById(R.id.EditText01);
        LV =(ListView控件)findViewById(android.R.id.list);
        上下文= getBaseContext();
        songManager =新SongsManager();
        songsList = songManager.getPlayList(上下文);
        AllSongs =新的ArrayList<字符串>();

        的for(int i = 0; I< songsList.size();我++){
            HashMap的<字符串,字符串>物镜= songsList.get(ⅰ);

            AllSongs.add(obj.get(songTitle));
        }
        AllSongsArray =新的String [AllSongs.size()];
        AllSongsArray = AllSongs.toArray(AllSongsArray);
        setListAdapter(新bsAdapter(本));
        et.addTextChangedListener(新TextWatcher(){
            公共无效afterTextChanged(编辑S){
                // TextWatcher接口的抽象方法。
            }

            公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数,
                    之后INT){
                // TextWatcher接口的抽象方法。
            }

            公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,
                    诠释计数){
                。=长度限制:Textlength et.getText()长度();
                AllSongs.clear();
                的for(int i = 0; I< AllSongsArray.length;我++){
                    如果(长度限制:Textlength&其中; = AllSongsArray [I] .length()){
                        / ***
                         *如果你想突出其启动国家
                         *与输入的字母,然后选择这个块。和
                         *发表评论,下面如果条件块
                         * /
                        / *
                         *如果(et.getText()的toString()。equalsIgnoreCase((字符串)
                         * listview_names [I] .subSequence(0,长度限制:Textlength))){
                         * array_sort.add(listview_names [I]);
                         * image_sort.add(listview_images [I]); }
                         * /

                        / ***
                         *如果你选择下面的块,然后它会像一个
                         *运营商一样在MySQL
                         * /

                        如果(AllSongsArray [I] .toLowerCase()。包括(
                                et.getText()的toString()。与toLowerCase()。修剪())){
                            AllSongs.add(AllSongsArray [I]);
                        }
                    }
                }
                AppendList(AllSongs);
            }

        });
        lv.setOnItemClickListener(新OnItemClickListener(){

            @覆盖
            公共无效onItemClick(适配器视图<>母公司视图中查看,
                    INT位置,长的id){
                // TODO自动生成方法存根
                Toast.makeText(getApplicationContext(),AllS​​ongs.get(位置),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.searching_class,菜单);
        返回true;
    }

    公共无效AppendList(ArrayList中<字符串> STR){
        setListAdapter(新bsAdapter(本));
    }

    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        //处理动作栏项目点击这里。将操作栏
        //自动在主/向上按钮操作的点击,只要
        //你在AndroidManifest.xml中指定一个父活动。
        INT的id = item.getItemId();
        如果(ID == R.id.action_settings){
            返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }

    公共类bsAdapter扩展了BaseAdapter {
        活动CNTX;

        公共bsAdapter(活动范围内){
            // TODO自动生成构造函数存根
            this.cntx =背景;

        }

        公众诠释getCount将(){
            // TODO自动生成方法存根
            返回AllSongs.size();
        }

        公共对象的getItem(INT位置){
            // TODO自动生成方法存根
            返回AllSongs.get(位置);
        }

        众长getItemId(INT位置){
            // TODO自动生成方法存根
            返回AllSongs.size();
        }

        公共查看getView(最终诠释的立场,观点convertView,
                ViewGroup中父){
            查看排= NULL;

            LayoutInflater充气= cntx.getLayoutInflater();
            行= inflater.inflate(R.layout.listview_item,NULL);

            TextView的电视=(TextView中)row.findViewById(R.id.tv_artist_name);

            tv.setText(AllSongs.get(位置));

            返回行;
        }
    }
}
 

解决方案

第一次添加两个功能的getData并设置数据搜索到baseadapter

 公共类bsAdapter扩展了BaseAdapter {
    活动CNTX;

    公共bsAdapter(活动范围内){
        // TODO自动生成构造函数存根
        this.cntx =背景;

    }

    公众诠释getCount将(){
        // TODO自动生成方法存根
        返回AllSongs.size();
    }

    公共对象的getItem(INT位置){
        // TODO自动生成方法存根
        返回AllSongs.get(位置);
    }

    众长getItemId(INT位置){
        // TODO自动生成方法存根
        返回AllSongs.size();
    }
    公共无效setDataSearch(字符串数据){
            this.search =数据;
    }

    公共字符串的getData(){
        返回this.search;
    }
 

先声明searchData在Search_class

 公共字符串searchData;
私人bsAdapter mAdapter;
 

和声明

  mAdapter =新bsAdapter(本);
 

那么你在文字观察家添加条件

 公共无效之前onTextChanged(CharSequence中,诠释开始,诠释,
                诠释计数){
            。=长度限制:Textlength et.getText()长度();
            AllSongs.clear();
            的for(int i = 0; I< AllSongsArray.length;我++){
                如果(长度限制:Textlength&其中; = AllSongsArray [I] .length()){
                    如果(AllSongsArray [I] .toLowerCase()。包括(
                            et.getText()的toString()。与toLowerCase()。修剪())){
                        AllSongs.add(AllSongsArray [I]);
                    }
                }
              如果(==长度限制:Textlength 0){

                     mAdapter.setDataSearch(空);

                } 其他 {

                    sea​​rchData = s.toString()与toLowerCase()。
                    mAdapter.setDataSearch(SearchData);
                }

         }
            AppendList(AllSongs);
        }
 

然后把这个功能baseadapter

 公共静态CharSequence的亮点(字符串搜索,字符串originalText){

       串normalizedText = Normalizer.normalize(originalText,Normalizer.Form.NFD).replaceAll(\\ p {InCombiningDiacriticalMarks} +,).toLowerCase();

       INT开始= normalizedText.indexOf(搜索);

       Spannable强调=新SpannableString(originalText);
        如果(开始℃,){
            //没有发现,没有向
            返回originalText;
        } 其他 {

            同时(开始> = 0){

                INT spanStart = Math.min(启动,originalText.length());
                INT spanEnd = Math.min(开始+ search.length(),originalText.length());

                highlighted.setSpan(新StyleSpan(android.graphics.Typeface.BOLD),spanStart,spanEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                highlighted.setSpan(新ForegroundColorSpan(cntx.getResources()的getColor(R.color.text_color_white)),spanStart,spanEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE。);
                启动= normalizedText.indexOf(搜索,spanEnd);
            }

            返回突出;
        }
    }
 

和把这个

 公开查看getView(最终诠释的立场,观点convertView,
            ViewGroup中父){
        查看排= NULL;

        LayoutInflater充气= cntx.getLayoutInflater();
        行= inflater.inflate(R.layout.listview_item,NULL);

        TextView的电视=(TextView中)row.findViewById(R.id.tv_artist_name);

        如果(搜索!= NULL){
                tv.setText(高亮(搜索,AllS​​ongs.get(位置));
            }
            否则,如果(搜索== NULL){
                tv.setText(AllSongs.get(位置));

            }


        返回行;
 

I Have a listview with arrayadapter .. i need to implement this in my music application ... help me out

    public class Search_Class extends Activity {

        EditText searchedit;
        ListView listview3;
        SongsManager songManager;
        Context context;
        String[] abc;
        ArrayList<String> names;
        ArrayList<String> arrayList;
        ArrayAdapter<String> ad;
        private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.my_search);
            context = getBaseContext();
            searchedit = (EditText) findViewById(R.id.searchedit);
            listview3 = (ListView) findViewById(R.id.listview3);
            songManager = new SongsManager();
            songsList = songManager.getPlayList(context);
            names = new ArrayList<String>();
            arrayList = new ArrayList<String>();

            for (int i = 0; i < songsList.size(); i++) {
                HashMap<String, String> obj = songsList.get(i);

                names.add(obj.get("songTitle"));
                arrayList.add(obj.get("songTitle"));
            }

            abc = new String[names.size()];
            abc = names.toArray(abc);

            listview3.setTextFilterEnabled(true);

            // ad = new ArrayAdapter<String>(MySearch.this,
            // android.R.layout.simple_list_item_1, abc);
            // listview3.setAdapter(ad);
            listview3.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // getting listitem index

                    String[] abc1 = new String[arrayList.size()];
                    abc1 = arrayList.toArray(abc);

                    int songIndex;

                    for (int i = 0; i < abc1.length; i++) {
                        if (abc[position].equalsIgnoreCase(abc1[i])) {
                            songIndex = i;
                            Intent in = new Intent(Search_Class.this,
                                    MainActivity.class);
                            // Sending songIndex to PlayerActivity
                            SharedPreferences sp;
                            sp = getSharedPreferences("lastplayed", MODE_PRIVATE);
                            Editor edit = sp.edit();
                            edit.putBoolean("searchSongIndex", true);
                            edit.commit();
                            in.putExtra("songIndex", songIndex);

                            in.putExtra("FLAG", true);
                            startActivity(in);
                            finish();

                            break;
                        }
                    }

                }

            });
            // ad.notifyDataSetChanged();

            searchedit.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                        int arg3) {
                    // TODO Auto-generated method stub
                    // MySearch.this.ad.getFilter().filter(arg0);

                    String text = arg0.toString().toLowerCase(Locale.getDefault());
                    filter(text);

                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    // TODO Auto-generated method stub

                }
            });

        }

        public void filter(String charText) {
            System.out.println("Text---" + charText);
            charText = charText.toLowerCase(Locale.getDefault());
            names.clear();
            if (charText.length() == 0) {
                System.out.println("if---" + arrayList.size());
                abc = new String[arrayList.size()];
                abc = arrayList.toArray(abc);

                // names.addAll(arrayList);
            } else {
                System.out.println("else");

                for (int i = 0; i < abc.length; i++) {

                    System.out.println(abc[i] + "----" + charText);

                    if (abc[i].toLowerCase(Locale.getDefault()).contains(charText)) {
                        names.add(abc[i]);
                    }
                }
                abc = new String[names.size()];
                abc = names.toArray(abc);
            }
            ad = new ArrayAdapter<String>(Search_Class.this,
                    android.R.layout.simple_list_item_1, abc);
            listview3.setAdapter(ad);
            ad.notifyDataSetChanged();
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // TODO Auto-generated method stub
            return false;
        }

    }

Just Created A Custom `Listview` Using `ListActivity` 

public class SearchingClass extends ListActivity {
    EditText et;
    ListView lv;
    Context context;
    ArrayList<String> AllSongs;
    String[] AllSongsArray;
    SongsManager songManager;
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    SearchClass_Adapter adapter;
    int textlength = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searching_class);
        et = (EditText) findViewById(R.id.EditText01);
        lv = (ListView) findViewById(android.R.id.list);
        context = getBaseContext();
        songManager = new SongsManager();
        songsList = songManager.getPlayList(context);
        AllSongs = new ArrayList<String>();

        for (int i = 0; i < songsList.size(); i++) {
            HashMap<String, String> obj = songsList.get(i);

            AllSongs.add(obj.get("songTitle"));
        }
        AllSongsArray = new String[AllSongs.size()];
        AllSongsArray = AllSongs.toArray(AllSongsArray);
        setListAdapter(new bsAdapter(this));
        et.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                // Abstract Method of TextWatcher Interface.
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // Abstract Method of TextWatcher Interface.
            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                textlength = et.getText().length();
                AllSongs.clear();
                for (int i = 0; i < AllSongsArray.length; i++) {
                    if (textlength <= AllSongsArray[i].length()) {
                        /***
                         * If you want to highlight the countries which start
                         * with entered letters then choose this block. And
                         * comment the below If condition Block
                         */
                        /*
                         * if(et.getText().toString().equalsIgnoreCase( (String)
                         * listview_names[i].subSequence(0, textlength))) {
                         * array_sort.add(listview_names[i]);
                         * image_sort.add(listview_images[i]); }
                         */

                        /***
                         * If you choose the below block then it will act like a
                         * Like operator in the Mysql
                         */

                        if (AllSongsArray[i].toLowerCase().contains(
                                et.getText().toString().toLowerCase().trim())) {
                            AllSongs.add(AllSongsArray[i]);
                        }
                    }
                }
                AppendList(AllSongs);
            }

        });
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), AllSongs.get(position),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.searching_class, menu);
        return true;
    }

    public void AppendList(ArrayList<String> str) {
        setListAdapter(new bsAdapter(this));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public class bsAdapter extends BaseAdapter {
        Activity cntx;

        public bsAdapter(Activity context) {
            // TODO Auto-generated constructor stub
            this.cntx = context;

        }

        public int getCount() {
            // TODO Auto-generated method stub
            return AllSongs.size();
        }

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

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return AllSongs.size();
        }

        public View getView(final int position, View convertView,
                ViewGroup parent) {
            View row = null;

            LayoutInflater inflater = cntx.getLayoutInflater();
            row = inflater.inflate(R.layout.listview_item, null);

            TextView tv = (TextView) row.findViewById(R.id.tv_artist_name);

            tv.setText(AllSongs.get(position));

            return row;
        }
    }
}

解决方案

first add two function getData and set Data Search to baseadapter

   public class bsAdapter extends BaseAdapter {
    Activity cntx;

    public bsAdapter(Activity context) {
        // TODO Auto-generated constructor stub
        this.cntx = context;

    }

    public int getCount() {
        // TODO Auto-generated method stub
        return AllSongs.size();
    }

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

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return AllSongs.size();
    }
    public void setDataSearch(String data) {
            this.search = data;
    } 

    public String getData() {
        return this.search;
    }

first declare searchData in Search_class

public String searchData;
private bsAdapter mAdapter;

and declare

mAdapter = new bsAdapter(this);

then you add condition in text watcher

  public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            textlength = et.getText().length();
            AllSongs.clear();
            for (int i = 0; i < AllSongsArray.length; i++) {
                if (textlength <= AllSongsArray[i].length()) {
                    if (AllSongsArray[i].toLowerCase().contains(
                            et.getText().toString().toLowerCase().trim())) {
                        AllSongs.add(AllSongsArray[i]);
                    }
                }
              if (textlength == 0) {

                     mAdapter.setDataSearch(null);

                } else {

                    searchData = s.toString().toLowerCase();
                    mAdapter.setDataSearch(SearchData);
                }

         }
            AppendList(AllSongs);
        }

and then put this function in baseadapter

public static CharSequence highlight(String search, String originalText) {

       String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();

       int start = normalizedText.indexOf(search);

       Spannable highlighted = new SpannableString(originalText);
        if (start < 0) {
            // not found, nothing to to
            return originalText;
        } else {

            while (start >= 0) {

                int spanStart   = Math.min(start, originalText.length());
                int spanEnd     = Math.min(start + search.length(), originalText.length());

                highlighted.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                highlighted.setSpan(new ForegroundColorSpan(cntx.getResources().getColor(R.color.text_color_white)), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                start = normalizedText.indexOf(search, spanEnd);
            }

            return highlighted;
        }
    }

and put this

public View getView(final int position, View convertView,
            ViewGroup parent) {
        View row = null;

        LayoutInflater inflater = cntx.getLayoutInflater();
        row = inflater.inflate(R.layout.listview_item, null);

        TextView tv = (TextView) row.findViewById(R.id.tv_artist_name);

        if(search != null){
                tv.setText(highlight(search,AllSongs.get(position));
            }
            else if (search == null){
                tv.setText(AllSongs.get(position));

            }


        return row;

这篇关于在搜索列表视图与搜索文本颜色列表视图中突出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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