android如何在listview中实现搜索功能

时间:2015-04-08 00:52:09

标签: android android-listview

我正在进行食谱应用的列表视图搜索。我一开始会使用getfilter,但失败了,无法修复。是否有任何其他方法来实现此功能。 这是我的Search.java:

public class Search extends Base{
ArrayList<Recipe> recipes;
ListView recipeListView;
RecipesAdapter adapter;
Context context;
int clickedrecipe;
EditText searchField;

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

    context = getApplicationContext();

    recipes = new ArrayList<Recipe>();
    adapter = new RecipesAdapter();
    recipeListView = (ListView) findViewById(R.id.RecipeListView);
    searchField = (EditText) findViewById(R.id.SearchField);

    new GetRecipe(context).execute();

    recipeListView.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Recipe recipe = recipes.get(position);

            Intent i = new Intent(context, Show.class);
            i.putExtra("name", recipe.name);
            i.putExtra("style_of_cooking", recipe.style_of_cooking);
            i.putExtra("ingredient", recipe.ingredient);
            i.putExtra("step", recipe.step);
            i.putExtra("image", recipe.image);
            i.putExtra("cost", recipe.cost);
            startActivity(i);
        }
    });


searchField.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        // Search.this.adapter.getFilter().filter(cs); 

        for(int i=0; i<recipes.size(); i++) {
            if (!recipes.get(i).name.contains(cs)) {
                recipes.remove(i);
                adapter.notifyDataSetChanged();
            }
        } 

    }


    @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                          
    }
});

}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menuLogout:
            logout();
            break;
    }
    return true;
}   

public class GetRecipe extends AsyncTask<String, Void, String> {

    private Context context;

    public GetRecipe(Context c){
        this.context = c;
    }

    protected void onPreExecute(){
        super.onPreExecute();
    }

    protected String doInBackground(String... params) {
        String result = "";
        try{
            result = BaseRest.serverGet("api/v1/recipes");
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result){
        super.onPostExecute(result);

        JSONArray jsonResult;

        try{
            jsonResult = new JSONArray(result);
            if(jsonResult != null){
                for(int i = 0; i < jsonResult.length(); i++){
                    JSONObject element = jsonResult.getJSONObject(i);{
                        if(element != null){
                            addEventToList(element);
                        }
                    }
                }
                recipeListView.setAdapter(adapter);
            }
        } catch (JSONException e){
            e.printStackTrace();
        }
    }

    private void addEventToList(JSONObject element) {
        try {
            Recipe recipe = new Recipe(
                    element.getString("id"),
                    element.getString("name"),
                    element.getString("user_id"),
                    element.getString("style_of_cooking"),
                    element.getString("ingredient"),
                    element.getString("step"),
                    element.getJSONObject("image").getString("url"),
                    element.getString("cost"),
                    element.getString("created_at"));
            recipes.add(recipe);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}


 class RecipesAdapter extends ArrayAdapter<Recipe> {
        public RecipesAdapter() {
            super(context, R.layout.row_recipe, recipes);
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if(itemView == null) {
                itemView = inflater.inflate(R.layout.row_recipe, parent, false);
            }

            final Recipe currentEvent = recipes.get(position);

            TextView recipeName = (TextView) itemView.findViewById(R.id.recipename);
            recipeName.setText(currentEvent.name);

            TextView time = (TextView) itemView.findViewById(R.id.timeContent);
            time.setText(currentEvent.created_at);


            return itemView;
        }

        @Override
        public int getCount() {
            return super.getCount();
        }
    }   

}

我在onTextChanged方法中使用for循环,它可以删除在edittext中输入内容时不相关的项目,但是当您删除输入时,listview无法返回初始状态。我该怎么写这个方法? 以下是我的Recipe.java:

公共课程食谱{

public String id;
public String name;
public String user_id;
public String style_of_cooking;
public String ingredient;
public String step; 
public String image; 
public String cost;
public String created_at;


/** Returned from server */
public Recipe(String id, String name, String user_id, String style_of_cooking, String ingredient, String step, String image, String cost, String created_at) {
    this.id = id;
    this.name = name;
    this.user_id = user_id;
    this.style_of_cooking = style_of_cooking;
    this.ingredient = ingredient;
    this.step = step;
    this.image = "http://192.168.0.17:3000" + image;
    this.cost = cost;
    this.created_at = created_at;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}
}

0 个答案:

没有答案