Custom ListView Adapter [Android]

后端 未结 2 1818
名媛妹妹
名媛妹妹 2021-01-15 10:58

I\'ve been stuck on a little bug trying to implement a custom listview in Java for an Android application.

I\'m trying to list a bunch words (typically, 100 < n &

相关标签:
2条回答
  • 2021-01-15 11:53

    It turned out the data was different than what I was expecting / thought it was. (Mayra, you were essentially correct).

    Otherwise the original code would have been functioning correctly.

    In the end, the getView(...) class looks like this:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    
        TextView view = (TextView) super.getView(position, convertView, parent);
    
        final String text = (String) view.getText();
    
        if(mHighlightSet.contains(text))
            view.setTextColor(Color.RED);
        else
            view.setTextColor(Color.WHITE);
    
        return view;
    }
    
    0 讨论(0)
  • 2021-01-15 11:59

    It might help if you test it out with a small number of words, so you can better see if you actually have a problem. I'm assuming that mAllWords is some sort of map. By doing mAllWords.keySet() you are getting the words in a random order. This probably makes it hard to tell if a word is actually there or not. You should try sorting the words there, or using some known ordered set so you can better tell whats going on.

    Also, in getView you do not want to be creating a TextView. This is really inefficient. Instead, you should get a view from the already inflated layout and update the styling. I.e, something like:

    public View getView(int position, View convertView, ViewGroup parent) {
      View view = super.getView(position, convertView, parent);
    
      TextView textView = view.findById(R.id.text);  // id of the text view in R.layout.simplerow
    
      String text = textView.getText();
    
      if(mHighlightSet.contains(text))
       view.setTextColor(Color.RED);
      else
       view.setTextColor(Color.WHITE);
    
      return view;
     }
    

    The super's getView will already fill in the correct word. You just want to update the styling in your getView method.

    0 讨论(0)
提交回复
热议问题