android - 如何在android中搜索项目后更新 ListView

标签 android listview search filter

目前我正在研究如何在为 edittext 中的项目指定关键字时从 ListView 中查找项目,现在我的“find”功能正常工作但在 toast 中显示找到的项目消息,并且 listview 定位的项目保持不变,如何更新我的 listivew 以获取其中的过滤结果。 这是我的代码

public class Home extends ListActivity {

//how many to load on reaching the bottom
int itemsPerPage = 15;
boolean loadingMore = false;                        

//For test data :-)
Calendar d = Calendar.getInstance();

ArrayList<String> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;



//ArrayList thats going to hold the search results
ArrayList<HashMap<String, String>> searchResults;
LayoutInflater inflater;
// All static variables
static final String URL = "http://india.abc.net/ads/?json=get_recent_posts";    
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";



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

    final EditText searchBox=(EditText) findViewById(R.id.search);
    final ListView  list=(ListView)findViewById(android.R.id.list);

    //get the LayoutInflater for inflating the customomView
    //this will be used in the custom adapter
    inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);


    final  ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

   // Creating JSON Parser instance
   final JSONParser jParser = new JSONParser();

   // getting JSON string from URL
       JSONObject json = jParser.getJSONFromUrl(URL);
                try {
                     posts = json.getJSONArray(KEY_POSTS);

        // looping through all song nodes <song>
                for(int i = 0; i < posts.length(); i++){
                    JSONObject c = posts.getJSONObject(i);
                    // Storing each json item in variable
                    String id = c.getString(KEY_ID);
                    String title = c.getString(KEY_TITLE);
                    String date = c.getString(KEY_DATE);
                    String content = c.getString(KEY_CONTENT);
                    // to remove all <P> </p> and <br /> and replace with ""
                     content = content.replace("<br />", "");
                     content = content.replace("<p>", "");
                     content = content.replace("</p>", "");

                    //authornumber is agin  JSON Object
                    JSONObject author = c.getJSONObject(KEY_AUTHOR);
                    String name = author.getString(KEY_NAME);

                    String url = null;
                    String slug = null;
                    try {
                    JSONArray atta = c.getJSONArray("attachments");
                    for(int j = 0; j < atta.length(); j++){
                        JSONObject d = atta.getJSONObject(j);

                        slug = d.getString(KEY_SLUG);

                        JSONObject images = d.getJSONObject(KEY_IMAGES);

                        JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
                        url = thumbnail.getString(KEY_URL);

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

                    }




            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(KEY_ID, id);
            map.put(KEY_TITLE, title);
            map.put(KEY_DATE, date);
            map.put(KEY_NAME, name);
            map.put(KEY_CONTENT, content);
            map.put(KEY_SLUG, slug);
            map.put(KEY_URL, url);


            // adding HashList to ArrayList
            songsList.add(map);
                }   
                }catch (JSONException e) {
                    e.printStackTrace();

                    }


              //searchResults=OriginalValues initially
                searchResults=new ArrayList<HashMap<String, String>>(songsList);


         // Getting adapter by passing json data ArrayList
            adapter=new LazyAdapter(this, songsList);    
             list.setAdapter(adapter);

             searchBox.addTextChangedListener(new TextWatcher() {

                 public void onTextChanged(CharSequence s, int start, int before, int count) {
                   //get the text in the EditText
                   String searchString=searchBox.getText().toString();
                   int textLength=searchString.length();

                          //clear the initial data set
                   searchResults.clear();

                   for(int i=0;i<songsList.size();i++)
                   {
                  String playerName=songsList.get(i).get("title").toString();

                  if(textLength<=playerName.length()){

                  //compare the String in EditText with Names in the ArrayList
                    if(searchString.equalsIgnoreCase(playerName.substring(0,textLength)))
                          Toast.makeText(getApplicationContext(),playerName,1).show();
                    searchResults.add(songsList.get(i));

                  }
                   }

                   adapter.notifyDataSetChanged();
                 }

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

                   }

                   public void afterTextChanged(Editable s) {

                   }
                  });

适配器类:

  public class LazyAdapter extends BaseAdapter {
  TextView title;
  private Activity activity;
  // private TextWatcher textWatcher;
  private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader; 

public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}


public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.activity_home, null);

    TextView title = (TextView)vi.findViewById(R.id.title); // title
    TextView date = (TextView)vi.findViewById(R.id.date); // artist name
    TextView content = (TextView)vi.findViewById(R.id.content);  // duration
    TextView name = (TextView)vi.findViewById(R.id.name); 
    // duration
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

    HashMap<String, String> song = new HashMap<String, String>();
    song = data.get(position);



    // Setting all values in listview
   title.setText(song.get(Home.KEY_TITLE));
    date.setText(song.get(Home.KEY_DATE));
    content.setText(song.get(Home.KEY_CONTENT));
    name.setText(song.get(Home.KEY_NAME));

   imageLoader.DisplayImage(song.get(Home.KEY_URL), thumb_image);
    return vi;
}


public void add(String string) {
    // TODO Auto-generated method stub

}
}

最佳答案

替换 searchBox.addTextChangedListener(new TextWatcher() {

} 通过

searchBox.addTextChangedListener(new TextWatcher() {

                 public void onTextChanged(CharSequence s, int start, int before, int count) {
                   //get the text in the EditText
                    searchString=searchBox.getText().toString();
                    textLength=searchString.length();
                   searchResults.clear();

                   for(int i=0;i<songsList.size();i++)
                   {
                   playerName=songsList.get(i).get("title").toString();
                  System.out.println("player name "+playerName);
                  if(textLength<=playerName.length()){
                  //compare the String in EditText with Names in the ArrayList
                    if(searchString.equalsIgnoreCase(playerName.substring(0,textLength))){
                    searchResults.add(songsList.get(i));
                    System.out.println("the array list is "+songsList.get(i));
                    adapter=new LazyAdapter(Home.this, searchResults);   

                     list.setAdapter(adapter);
                    }

                      }


                   }
                   if(searchResults.isEmpty()){
                       Toast toast= Toast.makeText(getApplicationContext(), 
                                  "No Items Matched", Toast.LENGTH_SHORT);  
                                  toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
                                  toast.show();
                   }
                   adapter.notifyDataSetChanged();
                 }

                 public void beforeTextChanged(CharSequence s, int start, int count,
                     int after) {
                 System.out.println("before changed");

                   }

                   public void afterTextChanged(Editable s) {


                                               System.out.println("after changed");
                   }
                  });

关于android - 如何在android中搜索项目后更新 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14847513/

相关文章:

c# - 为什么 Azure 搜索索引器会停止在 Live 应用程序上工作

arrays - 在一个非常大的数组中计算较小或相等元素的更快方法?

Javascript - 使用查找获取对象 ID

android - 无法为 APK 扩展解析符号 DownloaderService

android - Ionic/Cordova Web App - 启动时出现 index.html 错误

javascript - 显示到 ListView 问题

ListView 未使用自定义 ListItemComponent

android - 如何为谷歌地图嵌入式 Android 应用程序创建我自己的指纹供公众使用

android - 如何使用 Canvas 在位图图像上设置 onTouchEvent。

java - 包含图像和文本的 ListView 内存不足异常