Filtered list item opens the original list items&#

2020-05-07 06:36发布

问题:

After a tremendous amount of time searching in here, and everywhere else I am hopeless to find a solution.

So here is my problem.

I have created a list-view and on top of that I added a search-bar.

When I use the search-bar, to filter the results... when I click on item 7, instead of opening the specific clicked activity i.e. 7, it always starts from the first one.

I am looking forward to your help guys; because I need it!

回答1:

public class Group extends ListActivity {

 // ArrayList thats going to hold the search results
ArrayList<HashMap<String, Object>> searchResults;

 // ArrayList that will hold the original Data
ArrayList<HashMap<String, Object>> originalValues;
LayoutInflater inflater;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grouplist);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
ListView playersListView = (ListView) findViewById(android.R.id.list);


inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

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

inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// these arrays are just the data that
// I'll be using to populate the ArrayList
String names[] = {/*list of names*/ };
String teams[] = {/*list of teams*/};
Integer[] photos = {R.drawable.... /*list of drawables*/};
Integer[] id ={/*Position*/};

 originalValues = new ArrayList<HashMap<String, Object>>();

// temporary HashMap for populating the Items in the ListView
HashMap<String, Object> temp;

// total number of rows in the ListView
int noOfPlayers = names.length;

// now populate the ArrayList players
for (int i = 0; i < noOfPlayers; i++) {
temp = new HashMap<String, Object>();

temp.put("name", names[i]);
temp.put("team", teams[i]);
temp.put("photo", photos[i]);
temp.put("id", id[i]);

// add the row to the ArrayList
    originalValues.add(temp);
 }
    // searchResults=OriginalValues initially
  searchResults = new ArrayList<HashMap<String, Object>>(originalValues);

final CustomAdapter adapter = new CustomAdapter(this, R.layout.players, searchResults);

 // finally,set the adapter to the default ListView
playersListView.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 < originalValues.size(); i++) {
        String playerName = originalValues.get(i).get("name").toString();
        if (textLength <= playerName.length()) {
            // compare the String in EditText with Names in the
            // ArrayList
            if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
                searchResults.add(originalValues.get(i));
        }
    }

    adapter.notifyDataSetChanged();
}

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

}

public void afterTextChanged(Editable s) {

}
});


// listening to single list item on click
    playersListView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view,      int position, long id) {

        int pos=Integer.ParseInt(searchResults.get(position).get("id").toString());
             switch (pos) {
              case 0:
               Intent newActivity = new Intent(TeamsList.this, Barca.class);
               startActivity(newActivity);
               break;
              case 1:
               etc...
             }
       }
    }
 });

}

Custom adapter Class:

private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>> {

public CustomAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {

// let android do the initializing :)
super(context, textViewResourceId, Strings);
}

// class for caching the views in a row
private class ViewHolder {
ImageView photo;
TextView name, team;

}

ViewHolder viewHolder;

@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (convertView == null) {
    convertView = inflater.inflate(R.layout.players, null);
    viewHolder = new ViewHolder();

    // cache the views
    viewHolder.photo = (ImageView) convertView.findViewById(R.id.photo);
    viewHolder.name = (TextView) convertView.findViewById(R.id.name);
    viewHolder.team = (TextView) convertView.findViewById(R.id.team);

    //Take one textview in listview design named id
    viewHolder.id = (TextView) convertView.findViewById(R.id.id);


    // link the cached views to the convert view
    convertView.setTag(viewHolder);

  } else 
    viewHolder = (ViewHolder) convertView.getTag();

 int photoId = (Integer) searchResults.get(position).get("photo");

 // set the data to be displayed
viewHolder.photo.setImageDrawable(getResources().getDrawable(photoId));
viewHolder.name.setText(searchResults.get(position).get("name").toString());
viewHolder.team.setText(searchResults.get(position).get("team").toString());
viewHolder.id.setText(searchResults.get(position).get("id").toString());


// return the view to be displayed
return convertView;

    }
  }
}


回答2:

I think you cant find correct position on listview item click. so u can use one textview with visibility="Gone" and insert the position in that textview in every row. now u can easily access position while clicking on item with the value of textview which shows perfect position. Hope it works. Thanx



回答3:

The problem is that Adapter is populated once but with search results it gets overViewed by the searched items so on clicking it refers to the original items of list instead of the filtered list once , so we have to use the filtered lists' positions instead of the original one, i also faced this problem, try this:

In your listView.setOnItemClickListener

playersListView.setOnItemClickListener(new OnItemClickListener() {
 public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

    //Object objFilteredItem = parent.getItemAtPosition(position);
    //String a = searchResults.get(position);

    switch (Integer.parseInt((String) adapter.getItem(position))) {
    case 0:..
     Intent newActivity = new Intent(TeamsList.this,Barca.class);
     startActivity(newActivity);
     break;

    case 1:
     etc...
     break;
   }
 } 
});


回答4:

As from my previously answered question here, you have to override the getItem(position) method in your CustomAdapter. You are setting the onItemClick somewhat correctly but the list adapter doesn't know what exactly it's getting from getItem(position).

EDIT (details): You need to add something like this in your custom adapter -

@Override
public Object getItem(int position) {
    return list.get(position);
}

You should already have the list in your custom adapter. If not, you can add a list reference to your CustomAdapter:

private ArrayList<HashMap<String, Object>> list;

Then setting it using a setter in your Group activity:

customAdapter.setList(searchResults);