Search code examples
androidlistlistviewarraylistspanned

How put <Spanned> into list.setAdapter?


Simple but little tricky, if I have

list.setAdapter(new ArrayAdapter<String>(this,R.layout.double_row, R.id.doubleRow, articleItemsHelper));

it works if articleItemsHelper is String, but I wanna have HTML formatting in there so when articleItemsHelper is type Spanned this (adapter) doesn't work.

ArrayList<Spanned> articleItemsHelper = new ArrayList<Spanned>();

What's the solution?

EDIT: here is the solution - custom adapter

private static class SpannedAdapter extends BaseAdapter {
     private LayoutInflater mInflater;
     private ArrayList<Spanned> mArticleList;

     public SpannedAdapter(Context context, ArrayList<Spanned> articleList) {
        mInflater = LayoutInflater.from(context);
        mArticleList = articleList;
     }

     public int getCount() {
         return mArticleList.size();
     }

     public Object getItem(int position) {
         return position;
     }

     public long getItemId(int position) {
         return position;
     }

     public View getView(int position, View convertView, ViewGroup parent) {
         ViewHolder holder;
         if (convertView == null) {
             convertView = mInflater.inflate(R.layout.single_row, null);
             holder = new ViewHolder();
             holder.text = (TextView) convertView.findViewById(R.id.singleRow);

             convertView.setTag(holder);
         } else {
             holder = (ViewHolder) convertView.getTag();
         }

         holder.text.setText(mArticleList.get(position));

         return convertView;
     }

     static class ViewHolder {
         TextView text;
     }
}

Then just regularly call

list.setAdapter(new SpannedAdapter(this, articleItemsHelper));

where

articleItemsHelper

is

ArrayList<Spanned>

Solution

  • This is how ArrayAdapter set the text of the rows:

        T item = getItem(position);
        if (item instanceof CharSequence) {
            text.setText((CharSequence)item);
        } else {
            text.setText(item.toString());
        }
    

    As you can see, what it would do in your case is to call the toString method, and that's why it does not work. So, go ahead and write your own adapter, you have no choice in this case.