Search code examples
androidstringandroid-listviewarraylistandroid-arrayadapter

How to make ArrayAdapter populate 2 Arraylists within the same ListView


I want to make 2 ArrayList<Strings>s of the same length, appear, like this, in 1 ListView

Word 1 is a TextView that should be populated with 1 ArrayList<String> and Word 2 is another TextView that should be populated with a different ArrayList<String>

*These are TextViews, not Buttons

Word 1 is an <code>ArrayList</code>, Word 2 is another <code>ArrayList</code>

What should my ArrayAdaptor look like?

If this is a duplicate please send me a link.

CustomArrayAdapter.java that displays the same ArrayList<String> on both sides (Not what I need)

public class CustomArrayAdapter extends BaseAdapter {
Context context;
private ArrayList<String> words1;
private ArrayList<String> words2;

public CustomArrayAdapter(Context context, ArrayList<String> words1, ArrayList<String> words2) {
    this.words1 = words1;
    this.generates = words2;
    this.context = context;
}

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

    View v = convertView;

    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.list_item, null);
    }

    String a = (String) getItem(position);
    String b = (String) getItem(position);

    TextView tv1 = (TextView) v.findViewById(R.id.rhymed_word);
    TextView tv2 = (TextView) v.findViewById(R.id.generated_word);

    tv1.setText(a);
    tv2.setText(b);

    return v;

}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return words1.size();
}

@Override
public Object getItem(int position) {
    if (position >= words1.size())
        return words2.get(position);
    return words1.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

}


Solution

  • Ok, instead of using the Overridden method, just do this:

    TextView tv1 = (TextView) v.findViewById(R.id.rhymed_word);
    TextView tv2 = (TextView) v.findViewById(R.id.generated_word);
    
    tv1.setText(words1.get(position));
    tv2.setText(words2.get(position));
    
    return v;