Displaying ArrayList items in ListView contains 2 textviews

左心房为你撑大大i 提交于 2019-12-02 10:23:52

Its clear from your question that you want to display [a1, a2, b1, b2, c1, c2...] as

a1a2
b1b2
c1c2

so you need to change your code to following:

@Override
public int getCount() {
    // TODO Auto-generated method stub
    if(myList.size()%2==0)
        return mylist.size()/2;
    else
        return myList.size()/2+1;
}

and getView method as below:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    View List;
    if(convertView==null)
    {
        List=new View(context);
        LayoutInflater mLayoutinflater=(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        List=mLayoutinflater.inflate(R.layout.listitem_row, parent, false);
    }
    else
    {
        List=(View)convertView;

    }

    TextView t1=(TextView)List.findViewById(R.id.txtViewTitle);
    t1.setText((CharSequence) mylist.get(position*2));


    TextView t2=(TextView)List.findViewById(R.id.txtViewDescription);
    if(position*2<getCount())
           t2.setText(mylist.get(position*2+1).toString());


    return List;
}

your adapter getview is perfect, but your logic is wrong.. I would prefer making class object with 2 strings, like.

public class MyClass
{
  String one;
  String two;
}

and make your list like

ArrayList<MyClass> mylist = new ArrayList<MyClass>();

and then setText like you want.

TextView t1=(TextView)List.findViewById(R.id.txtViewTitle);
t1.setText(mylist.get(position).one);           //String one= "a1" according to position in mylist
                                                //it will be = "b1" on next position
                                              //no need of casting to CharSequence

TextView t2=(TextView)List.findViewById(R.id.txtViewDescription);
t2.setText(mylist.get(position).two);           //String two= "a2"

You have wrong implementation in some of the adapter methods.

getItem() should return the object from your list at the position:

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

Then, in getView

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //  Create view
    //   ...

    String[] item = (String[])getItem(position);  //  Get the current object at 'position'


    //  Update your view here
    TextView t1=(TextView)List.findViewById(R.id.txtViewTitle);
    t1.setText(item[0]);

    TextView t2=(TextView)List.findViewById(R.id.txtViewDescription);
    t2.setText(item[1]);
}

If your want to display two different strings, I suggest you list should look like this

[new String[]{"a1", "a2"}, new String[]{"b1", "b2"}, ...]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!