Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过列表视图在android actionbar中执行过滤搜索_Java_Android_Listview_Android Actionbar_Searchview - Fatal编程技术网

Java 通过列表视图在android actionbar中执行过滤搜索

Java 通过列表视图在android actionbar中执行过滤搜索,java,android,listview,android-actionbar,searchview,Java,Android,Listview,Android Actionbar,Searchview,我正在尝试在我的应用程序的操作栏中创建一个搜索视图,该视图将在应用程序的列表视图上执行搜索(即根据键入的字母显示列表视图中项目的名称)。Listview使用listadapter类。当我在“搜索”视图中输入文本时,什么也没有发生。我对“搜索视图”非常陌生,尝试使用从网上获得的代码,但没有任何帮助:(你能建议我怎么做吗?我应该为它创建另一个类吗 这是我的密码: ListAdapter.java public class ListAdapter extends BaseAdapter{ V

我正在尝试在我的应用程序的操作栏中创建一个搜索视图,该视图将在应用程序的列表视图上执行搜索(即根据键入的字母显示列表视图中项目的名称)。Listview使用listadapter类。当我在“搜索”视图中输入文本时,什么也没有发生。我对“搜索视图”非常陌生,尝试使用从网上获得的代码,但没有任何帮助:(你能建议我怎么做吗?我应该为它创建另一个类吗

这是我的密码:

ListAdapter.java

public class ListAdapter extends BaseAdapter{
     Vector listData = null;

        public void setData(Vector data) {
            listData = data;
        }

    private Context _context;
    private List<String> list;
     ViewHolder holder=null;
        View row=null;

    public  ListAdapter(Context _context,List<String> list)
    {
        this._context=_context;
        this.list=list;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

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

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

        public int getViewTypeCount() {

         return getCount();

        }

        @Override

        public int getItemViewType(int position) {

         return position;
        }

        private static class ViewHolder
        {
            public TextView textView;


            public ViewHolder(View row) {
                // TODO Auto-generated constructor stub
                 textView = (TextView) row.findViewById(R.id.rowTextView);

            }

        }



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

        row=convertView;
        holder=null;

           try{


               if(row==null)
               {
                   LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    row = inflater.inflate(R.layout.simplerow, viewGroup, false);
                   holder=new ViewHolder(row);
                     row.setTag(holder);
                     Log.d("newrow", "New row");

          /*/View row = convertView;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.simplerow, viewGroup, false);
            }


            TextView textView = (TextView) row.findViewById(R.id.rowTextView);*/
            holder.textView.setText(list.get(position).toString());

               }
            else
            {

                 holder= (ViewHolder) row.getTag();
                 Log.d("recycle", "Recycling stuff");

            }
               }
               catch(Exception e)
                {
                    e.printStackTrace();

                }


           try
           {
               if(row!=null)
               {
                   if(position==MainActivity.selected_item)
                   {
                     row.setBackgroundColor(Color.RED);
                   }
                   else
                   {
                       row.setBackgroundColor(Color.BLACK);
                   }
               }
           }
           catch(Exception e)
           {

           }

            return row;

    }
    public Filter getFilter() {
        // TODO Auto-generated method stub

        return null;
    }


    }
公共类ListAdapter扩展了BaseAdapter{
向量listData=null;
公共数据(矢量数据){
listData=数据;
}
私人语境(private Context)(私人语境);;
私人名单;
ViewHolder=null;
视图行=空;
公共ListAdapter(上下文_上下文,列表)
{
这个。上下文=\u上下文;
this.list=list;
}
@凌驾
public int getCount(){
//TODO自动生成的方法存根
返回list.size();
}
@凌驾
公共对象getItem(int arg0){
//TODO自动生成的方法存根
返回列表。获取(arg0);
}
@凌驾
公共长getItemId(int arg0){
//TODO自动生成的方法存根
返回arg0;
}
@凌驾
public int getViewTypeCount(){
返回getCount();
}
@凌驾
public int getItemViewType(int位置){
返回位置;
}
私有静态类视图持有者
{
公共文本视图文本视图;
公共视图持有者(视图行){
//TODO自动生成的构造函数存根
textView=(textView)row.findViewById(R.id.rowTextView);
}
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组视图组){
//TODO自动生成的方法存根
行=转换视图;
holder=null;
试一试{
if(行==null)
{
LayoutInflater充气器=(LayoutInflater)\u context.getSystemService(context.LAYOUT\u充气器\u SERVICE);
row=充气机。充气(R.layout.simplerow,viewGroup,false);
支架=新的视图支架(行);
row.setTag(支架);
Log.d(“新行”、“新行”);
/*/视图行=转换视图;
if(convertView==null){
LayoutInflater充气器=(LayoutInflater)\u context.getSystemService(context.LAYOUT\u充气器\u SERVICE);
row=充气机。充气(R.layout.simplerow,viewGroup,false);
}
TextView TextView=(TextView)row.findViewById(R.id.rowTextView)*/
holder.textView.setText(list.get(position.toString());
}
其他的
{
holder=(ViewHolder)row.getTag();
Log.d(“回收”,“回收材料”);
}
}
捕获(例外e)
{
e、 printStackTrace();
}
尝试
{
如果(行!=null)
{
如果(位置==MainActivity.selected_项)
{
行.背景色(颜色.红色);
}
其他的
{
行.背景色(颜色.黑色);
}
}
}
捕获(例外e)
{
}
返回行;
}
公共过滤器getFilter(){
//TODO自动生成的方法存根
返回null;
}
}
MainActivity.java

public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {

    ListView list;
    ArrayAdapter<String> adapter ;
    ListAdapter listAdapter;
    ArrayList<String> listTest;
     ArrayList<String> listSoundNames;
    ImageButton play,stop,back,next;
    String songpath,song,title;
    int index,current_position;
    File[] listFile;
    SharedPreferences sharedPref;
    MediaPlayer mp,mp2;
    ActionBar bar;
    private Boolean state=false;
    private static int save = -1;
    int count=0;
    private static final String TAG = MainActivity.class.getSimpleName();
    private Context _context = this;
    public static int selected_item=-1;



    @Override
    protected void onCreate(Bundle savedInstanceState) {



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        song = sharedPref.getString("songname", "name");

        mp=new MediaPlayer();
        mp2 = new MediaPlayer();

        mp.setOnCompletionListener(this);


        list = (ListView)findViewById(R.id.list);
        //list.setTextFilterEnabled(true);
        list.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

        _context=this;

        adapter = new ArrayAdapter<String>(_context,R.layout.simplerow, listSoundNames);


        listTest = new ArrayList<String>( );
        listSoundNames=new ArrayList<String>();

        play = (ImageButton)findViewById(R.id.play);
        back = (ImageButton)findViewById(R.id.prev);
        next = (ImageButton)findViewById(R.id.next);

        //adding listeners
        play.setOnClickListener(this);
        back.setOnClickListener(this);
        next.setOnClickListener(this);


        //action bar controls
        bar = getActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
        //bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent))); 

        EditText editText = new EditText(getApplicationContext());
        getActionBar().setCustomView(editText);


        //bar.setDisplayShowTitleEnabled(true);
        //bar.setDisplayHomeAsUpEnabled(true);

        Scanner("/sdcard/");//storage path


        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if(listTest.size() != 0)
        {
            //listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);

            listAdapter=new ListAdapter(_context,listSoundNames);
            list.setAdapter(listAdapter);
            list.setOnItemClickListener(new OnItemClickListener() 
            {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            {
                //////////////////changing list item background on click///////////////////


                //list.setSelection(position);
                view.setSelected(true);
                ///////////////////PROBLEM/////////////

                for(int a = 0; a < parent.getChildCount(); a++)
                {
                    list.clearChoices();
                    parent.getChildAt(a).setBackgroundColor(Color.BLACK);


                }

                selected_item=position;
               // view.setBackgroundColor(Color.RED);


                ////////////////////////////////////////////////////////////////////////////
                //accessing song path
                String selected = listTest.get(position);
                list.setItemChecked(position, true);
                list.setSelection(position);

                //accessing the song name
                String name = (String) ((TextView) view).getText();
                title = name;
                //bar.setTitle(title);
                //Log.e(TAG, name);

                Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
                try{
                    mp.reset();
                    mp.setDataSource(listTest.get(position));//source
                    mp.prepare();
                    mp.start();
                    index = position;
                    play.setImageResource(R.drawable.pause);
                    }
                catch(Exception e){e.printStackTrace();}



            }


            });




            }

        }



        ////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////*Songs added here to list*////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////

        private void Scanner(String path) {
            // TODO Auto-generated method stub
            {
                try 
                {
                        File fl = new File(path);
                        File[] listOfFiles = fl.listFiles();              

                        for (File listOfFile : listOfFiles)
                         {
                            String s = listOfFile.getName();

                            if(s.endsWith(".mp3"))
                            {

                            songpath = listOfFile.getPath();
                            listTest.add(songpath);//adding song names to list
                            //listTest.toString().replaceFirst(songpath, s);



                            // store file name in listSoundNames
                            int pos = s.lastIndexOf(".");
                            if (pos > 0)
                            {
                                song = s.substring(0, pos);
                            }
                            listSoundNames.add(song);

                            }


                            /////////////////////////////////
                            File f = new File(path+s+"/");
                            if (f.exists() && f.isDirectory()) {
                            Scanner(path+s+"/");
                            }
                            ////////////////////////////////


                        }



                }
            catch (Exception e) { }
            }

            }








    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if (v.equals(play))
        {
            if(mp.isPlaying())
            {
                mp.pause();
                Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
                //change in button image//
                play.setImageResource(R.drawable.play);

            }
            else
            {
                mp.start();
                Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
                //change in button image//
                play.setImageResource(R.drawable.pause);
                //
            }
        }


            if (v.equals(back))
            {
                mp.stop();
                mp.reset();
                //bar.setTitle(song);
                if(index!=0)
                {
                index = index -1;
                }
                else
                {
                    index = (list.getAdapter().getCount()-1)-1;

                }

                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
                try {


                    mp.setDataSource(getApplicationContext(), uri);//setting new data source 


                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    mp.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }        
                mp.start();//PROBLEM: NOT PLAYING
                Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();

            }


            if (v.equals(next))
            {

                mp.stop();
                mp.reset();
                index = index +1;


                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song

                try {


                    mp.setDataSource(getApplicationContext(), uri);//setting new data source 


                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    mp.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }        
                mp.start();//PROBLEM: NOT PLAYING
                Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();


            }


    }


    @Override
    public void onCompletion(MediaPlayer arg0) {
        // TODO Auto-generated method stub
        play.setImageResource(R.drawable.play);
    }

    /*@Override
    protected void onStop() {
        super.onStop();
        mp.stop();
        Toast.makeText(getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();

    }*/

    //////////////////////////////////////////Search box/////////////////////////////////////////////////////



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);



         SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

                searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
                searchView.setIconifiedByDefault(false);   
                searchView.setQueryHint(Html.fromHtml(("<font color = #ffffff>"+"Listen Now"+"</font>")));



            SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() 
            {
                @Override
                public boolean onQueryTextChange(String newText) 
                {
                    // this is your adapter that will be filtered
                    //listAdapter.getFilter().filter(newText);

                    Toast.makeText(getApplicationContext(), "type"+newText, Toast.LENGTH_SHORT).show();
                    return true;
                }
                @Override
                public boolean onQueryTextSubmit(String query) 
                {
                    // this is your adapter that will be filtered
                    //((Filterable) listAdapter).getFilter().filter(query);
                    //listAdapter.getFilter().filter(query);
                    Toast.makeText(getApplicationContext(), query, Toast.LENGTH_SHORT).show();

                   /* try 
                    {
                            File fl = new File("/sdcard/");
                            File[] listOfFiles = fl.listFiles();  
                            String selectedPath="";

                            for (File listOfFile : listOfFiles)
                             {
                                String s = listOfFile.getName();

                                if(s.equalsIgnoreCase(query) && s.endsWith(".mp3"))
                                {

                                    selectedPath= listOfFile.getPath();//not receiving the path:PROBLEM:HOLDING THE POSITION FOR LIST ITEM


                                //listTest.add(songpath);//adding song names to list
                                //listTest.toString().replaceFirst(songpath, s);
                                Toast.makeText(getApplicationContext(), listOfFile.getPath(), Toast.LENGTH_SHORT).show();

                                /*mp.setDataSource(selectedPath);
                                mp.prepare();
                                mp.start();

                                }



                                /////////////////////////////////
                                File f = new File("/sdcard/"+s+"/");
                                if (f.exists() && f.isDirectory()) {
                                Scanner("/sdcard/"+s+"/");
                                }
                                ////////////////////////////////


                            }



                    }

                catch (Exception e) { }*/

                    return true;
                    }
            };
            searchView.setOnQueryTextListener(textChangeListener);



            return super.onCreateOptionsMenu(menu);

    }


}
public类MainActivity扩展活动实现视图。OnClickListener,OnCompletionListener{
列表视图列表;
阵列适配器;
列表适配器列表适配器;
阵列列表测试;
ArrayList声音名称;
图像按钮播放、停止、后退、下一步;
字符串路径、歌曲、标题;
int索引,当前位置;
文件[]列表文件;
SharedPreferences sharedPref;
MediaPlayer mp,mp2;
ActionBar;
私有布尔状态=false;
私有静态int save=-1;
整数计数=0;
私有静态最终字符串标记=MainActivity.class.getSimpleName();
私有上下文_Context=this;
公共静态int selected_item=-1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
song=sharedPref.getString(“songname”、“name”);
mp=新媒体播放器();
mp2=新媒体播放器();
mp.setOnCompletionListener(此);
list=(ListView)findViewById(R.id.list);
//list.setTextFilterEnabled(true);
list.setChoiceMode(ListView.CHOICE\u MODE\u SINGLE);
_上下文=这个;
适配器=新的ArrayAdapter(_context,R.layout.simplerow,listSoundNames);
listTest=newArrayList();
listSoundNames=newArrayList();
play=(图像按钮)findViewById(R.id.play);
后退=(图像按钮)findViewById(R.id.prev);
next=(ImageButton)findViewById(R.id.next);
//添加侦听器
play.setOnClickListener(这个);
back.setOnClickListener(this);
next.setOnClickListener(this);
//操作栏控件
bar=getActionBar();
杆件退根拉深(新的彩色拉深(Color.parseColor(#DF0174”));
//setIcon(新的ColorDrawable(getResources().getColor(android.R.color.transparent));
EditText EditText=新的EditText(getApplicationContext());
getActionBar().setCustomView(编辑文本);
//bar.setDisplayShowTitleEnabled(真);
//bar.setDisplayHomeAsUpEnabled(真);
扫描仪(“/sdcard/”;//存储路径
<android.support.v7.widget.SearchView
        android:id="@+id/mSearchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:searchIcon="@android:drawable/ic_menu_search"
        app:defaultQueryHint="@string/search_hint"/>
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // your code when you submit your search
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) { 
                // your code when you type on your searchview
                return true;
            }
        });