2012-06-07 3 views
0

Я пытался узнать о списках и других вещах в android .. У меня есть приложение, которое показывает список элементов с SD-карты. Мне нужен код, для которого я могу добавить опцию сортировки. сортировать список по имени, дате, типу ans. пожалуйста, помогите мне. il отображает мой код здесь .., который показывает содержимое в виде списка.Как добавить опцию сортировки в мое приложение?

package com.android.sam; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 

import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener ; 
import android.widget.BaseAdapter; 
import android.widget.Gallery; 
import android.widget.ImageView; 

import java.util.ArrayList; 
import java.util.List; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.ListActivity; 

import android.content.Context; 
import android.content.DialogInterface; 
import android.database.Cursor; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 

public class SamActivity extends ListActivity { 

private List<String> item = null; 

private List<String> path = null; 

private String root="/"; 

private TextView myPath; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
    myPath = (TextView)findViewById(R.id.path); 
getDir(root); 
} 
private void getDir(String dirPath) 

{ 

myPath.setText("Location: " + dirPath); 



item = new ArrayList<String>(); 

path = new ArrayList<String>(); 



File f = new File(dirPath); 

File[] files = f.listFiles(); 



if(!dirPath.equals(root)) 

{ 



    item.add(root); 

    path.add(root); 



    item.add("../"); 

    path.add(f.getParent()); 



    } 



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

    { 

    File file = files[i]; 

    path.add(file.getPath()); 

    if(file.isDirectory()) 

    item.add(file.getName() + "/"); 

    else 

    item.add(file.getName()); 

    } 



    ArrayAdapter<String> fileList = 

    new ArrayAdapter<String>(this, R.layout.row, item); 

    setListAdapter(fileList); 

    } 
@Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
File file = new File(path.get(position)); 
if (file.isDirectory()) 

{ 

if(file.canRead()) 

getDir(path.get(position)); 

else 

{ 

new AlertDialog.Builder(this) 

.setIcon(R.drawable.ic_launcher) 

.setTitle("[" + file.getName() + "] folder can't be read!") 

.setPositiveButton("OK", 

    new DialogInterface.OnClickListener() { 

public void onClick(DialogInterface dialog, int which) { 

    // TODO Auto-generated method stub 

    } 

    }).show(); 

    } 

    } 

else 

{ 

    new AlertDialog.Builder(this) 

.setIcon(R.drawable.alert) 

.setTitle("[" + file.getName() + "] ") 

.setPositiveButton("OK", 

    new DialogInterface.OnClickListener() { 

    public void onClick(DialogInterface dialog, int which) { 

    // TODO Auto-generated method stub 

    } 

    }).show(); 

    } 

    } 

    } 

в моем макете я добавил кнопку изображения, которые должны быть показаны параметры сортировки и сортировки списка Thankx заранее это то, что я ВГА добавил `сортировочные = (Button) findViewById (R.id .button2); final Контекстный контекст1 = это; sorting.setOnClickListener (новый OnClickListener() {

 public void onClick(View v) { 

      if (v == findViewById(R.id.button2)) { 

       final CharSequence[] items = {"name", "date", "size", "type", "none"}; 

       AlertDialog.Builder builder = new AlertDialog.Builder(context1); 

       builder.setTitle("Sort by"); 

       builder.setSingleChoiceItems(items, -1, new         DialogInterface.OnClickListener  ()  { 
        // Click listener 
        public void onClick(DialogInterface dialog, int item) { 
         Toast.makeText(getApplicationContext(), items[item],   Toast.LENGTH_SHORT).show(); 
         //If the Cheese item is chosen close the dialog box 
         if(items[item]=="none") 
          dialog.dismiss(); 
        } 
       }); 
       AlertDialog alert = builder.create(); 
       //display dialog box 
       alert.show(); 
      } 
     } 
     }); 
+0

Collections.sort (item); но ищете их снова, если пользователь нажмет на любую кнопку? –

+0

http://stackoverflow.com/questions/5815060/sorting-arraylist-of-string-in-android –

+0

спасибо dheeresh singh :) но где я могу добавить это? – sheekha

ответ

0

1- это вы хотите отсортировать ArrayList объекта Струнный только из ArrayList можно использовать Collections.sort (пункт);

2- если вы есть ArrayList вашего объекта типа необходимости создания компаратора для этого.

http://www.developer.com/java/other/article.php/858411/Data-Structures-in-Java-Part-9-The-Comparator-Interface-Part-1.htm

java-sorting-comparator-vs-comparable

+0

Я добавил этот диалог ... – sheekha

+0

? любая проблема? ..... –

+0

Где я могу добавить, что Collections.sort (item) в моем коде? – sheekha

Смежные вопросы