2017-01-29 7 views
-3

Как сделать поиск в ListView?Как сделать поиск в listview (фрагмент андроида)?

listView.setFilterText(newText); 

не работает.

Любые идеи исправить это?

У меня есть ListView с одним Я добавляю несколько файлов. Я хочу сделать поиск в этих файлах и показать пользователям файл.

Вы можете посмотреть на скриншоте:

enter image description here

FragmentFolder.java:

public class FragmentFolder extends Fragment{ 

    static Context context; 
    public static Fragment fragment; 
    ListView listView; 
    private File currentFolder; 
    private FileArrayAdapter fileArrayListAdapter; 
    private FileFilter fileFilter; 
    private File fileSelected; 
    private ArrayList<String> extensions; 
    SharedPreferences sPref; 
    boolean checker; 
    Bitmap bmThumbnail; 
    ImageView img; 
    String path; 
    boolean good = false; 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.fragment_foler, container, false); 
     context = v.getContext(); 
     fragment = this; 
//TODO: ЧТОБЫ БЫЛО ВИДНО ПОИСК - УБЕРИ КОММЕНТАРИИ 
     setHasOptionsMenu(true); 
     SharedPreferences sharedPrefs = getActivity().getSharedPreferences("com.fug.video.player", MODE_PRIVATE); 
     checker = sharedPrefs.getBoolean("filefilter", true); 

     listView = (ListView)v.findViewById(R.id.gridView); 
     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       FileInfo fileDescriptor = fileArrayListAdapter.getItem(position); 
       if (fileDescriptor.isFolder() || fileDescriptor.isParent()) { 
        currentFolder = new File(fileDescriptor.getPath()); 
        fill(currentFolder); 
       } else { 
        /** Нужно проверить на расширение файла */ 
        fileSelected = new File(fileDescriptor.getPath()); 
        Intent intent = new Intent(context, PlayerActivity.class); 
        intent.putExtra("DATA", fileSelected.getAbsolutePath()); 
        context.startActivity(intent); 
        Log.i("FILE CHOOSER", "result ok"); 
       } 
       } 
     }); 

     currentFolder = new File(Environment.getExternalStorageDirectory() 
       .getAbsolutePath()); 
     fill(currentFolder); 

     return v; 
    } 

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

     MenuItem searchItem = menu.findItem(R.id.action_search); 
     SearchView searchView = (SearchView) searchItem.getActionView(); 
     SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE); 
     if(null!=searchManager) { 
      searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName())); 
     } 
     searchView.setIconifiedByDefault(false); 
     searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 
      @Override 
      public boolean onQueryTextSubmit(String query) { 
       //listView.setFilterText(query.toString()); 
       return false; 
      } 

      @Override 
      public boolean onQueryTextChange(String newText) { 
       //Поиск realtime 
       listView.setFilterText(newText); 
       return true; 
      } 

     }); 
     super.onCreateOptionsMenu(menu, inflater); 
    } 

    private void fill(File f) { 
     File[] folders = null; 
     if (fileFilter != null) 
      folders = f.listFiles(fileFilter); 
     else 
      folders = f.listFiles(); 

     //this.setTitle(getString(R.string.currentDir) + ": " + f.getName()); 
     List<FileInfo> dirs = new ArrayList<FileInfo>(); 
     List<FileInfo> files = new ArrayList<FileInfo>(); 
     try { 
      for (File file : folders) { 
       if (file.isDirectory() && !file.isHidden()) 
        //si es un directorio en el data se ponemos la contante folder 
        dirs.add(new FileInfo(file.getName(), 
          Constants.FOLDER, file.getAbsolutePath(), 
          true, false)); 
       else { 

        if (!file.isHidden()) { 
         if (file.getName().endsWith(Constants.MP4) ||file.getName().endsWith(Constants.MOV) ||file.getName().endsWith(Constants.M4V) ||file.getName().endsWith(Constants.FLV) || file.getName().endsWith(Constants.AVI) || file.getName().endsWith(Constants.GPP3) || file.getName().endsWith(Constants.WEBM) || file.getName().endsWith(Constants.MAT)) { 
          // bmThumbnail = ThumbnailUtils.createVideoThumbnail(file.getPath(), MediaStore.Video.Thumbnails.MINI_KIND); 
          path = file.getPath(); 

          files.add(new FileInfo(file.getName(), 
            getString(R.string.fileSize) + ": " 
              + file.length(), 
            file.getAbsolutePath(), false, false)); 
//         good = true; 
          //img.setImageBitmap(bmThumbnail); 


//       Glide.with(context) 
//        .load(file) 
//        .into(img); 
         } 
        } 
//     else { 
//      //Showall files 
//      files.add(new FileInfo(file.getName(), 
//        getString(R.string.fileSize) + ": " 
//          + file.length(), 
//        file.getAbsolutePath(), false, false)); 
//     } 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     Collections.sort(dirs); 
     Collections.sort(files); 
     dirs.addAll(files); 
     if (!f.getName().equalsIgnoreCase(
       Environment.getExternalStorageDirectory().getName())) { 
      if (f.getParentFile() != null) 
       //si es un directorio padre en el data se ponemos la contante adeacuada 
       dirs.add(0, new FileInfo("..", 
         Constants.PARENT_FOLDER, f.getParent(), 
         false, true)); 
     } 

     fileArrayListAdapter = new FileArrayAdapter(context, 
       R.layout.file_row, dirs); 
     listView.setAdapter(fileArrayListAdapter); 
    } 

} 
+0

Хотите полный на поиск файлов вы? –

+1

Так в чем проблема? – Gattsu

ответ

0

Попробуйте использовать код, приведенный ниже, это будет работать для вас.

Это функция, которую я пишу для вас, вам нужно вызвать эту функцию и передать путь к ней ... затем он будет искать имя файла с нужным поисковым словом и возвращать список массивов файлов которые имеют эти имена.

public void walkdir(File dir) { 
    String sPattern = "searching_word"; 

    File listFile[] = dir.listFiles(); 

    if (listFile != null) { 
     for (int i = 0; i < listFile.length; i++) { 

      if (listFile[i].isDirectory()) { 
       walkdir(listFile[i]); 
      } else { 
       if (listFile[i].getName().startsWith(sPattern)){ 

       //Display that file in list 

       } 
      } 
     } 
    }  
} 

Чтобы произвести поиск по всей SDCard вызов этой функции с использованием

walkdir(Environment.getExternalStorageDirectory()); 
+0

Где прочесть этот код: walkdir (Environment.getExternalStorageDirectory()) ;? А что писать на // Отобразить этот файл в списке? Help pls, я не могу понять – Simon

+0

@Simon это функция, которую я пишу для вас, вам нужно вызвать эту функцию и передать путь к ней ... затем он будет искать имя файла с нужным поисковым словом и возвращать список массивов файлов, которые имеют эти имена. – Gattsu

+0

'walkdir (Environment.getExternalStorageDirectory()); этот код означает, что вы передаете корневой путь dir к функции и в кодовом блоке' // Покажите этот файл в списке', вы должны сами написать логику для добавления этого массива файлов в ListView и их отображение. – Gattsu