Skip to content Skip to sidebar Skip to footer

Set A String Array Into Bold In Android

I have a ListView where I managed to display many texts on it. Some of the texts are formatted as BOLD. In order to make those texts bold, I used Spannable and it works! However, w

Solution 1:

Create custom adapter and implement ViewHolder pattern to maintain List each item state:

class CustomAdapter extends ArrayAdapter<String>{
        private Context context;
        private String[] source;
        public CustomAdapter(Context context, String[] source) {
            super(context,R.layout.items,source);
            this.context = context;
            this.source = source;
        }

        @Override
        public int getCount() {
            return source.length;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(convertView==null){
                convertView = LayoutInflater.from(context).inflate(R.layout.items,null);
                holder = new ViewHolder();
                holder.tv = (TextView) convertView.findViewById(R.id.lbl_item);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder)convertView.getTag();
            }

            if(position==0){
                final SpannableString out0 = new SpannableString(source[position]);
                StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
                out0.setSpan(boldSpan, 6, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.tv.setText(out0);

            }else if(position==2){
                final SpannableString out2 = new SpannableString(source[position]);
                StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
                out2.setSpan(boldSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.tv.setText(out2);
            }else{
                holder.tv.setText(source[position]);
            }


            convertView.setTag(holder);
            return convertView;
        }

        private class ViewHolder {
            TextView tv;
        }
    }

Post a Comment for "Set A String Array Into Bold In Android"