我有一个ListView,我设法在其上显示许多文本。部分文本格式为 BOLD 。为了使这些文本变得粗体,我使用了Spannable并且它有效!但是,当我向下滚动它时,索引[0]变为多个。
为了避免那个场景,我使用了一个持有人来保存我的TextViews。我设法在滚动中解决了这个问题,但由于某些原因,文本样式是BOLD,在我的ListView中消失了。我怎么能这样做?
MainActivity.java
private void populateListView() {
String[] source = { "Lorem ipsum dolor sit amet", "consectetuer adipiscing elit",
"sed diam nonummy nibh " };
final SpannableString out0 = new SpannableString(source[0]);
final SpannableString out2 = new SpannableString(source[2]);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
out0.setSpan(boldSpan, 6, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out2.setSpan(boldSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.items, // Layout to use (create)
source) { // Items to be displayed
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
try {
viewHolder.tv = (TextView) lv_procedures.getChildAt(0)
.findViewById(R.id.lbl_item);
viewHolder.tv_2 = (TextView) lv_procedures.getChildAt(2)
.findViewById(R.id.lbl_item);
viewHolder.tv.setText(out0);
viewHolder.tv_2.setText(out2);
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
};
}
Class ViewHolder
private class ViewHolder {
TextView tv;
TextView tv_2;
}
答案 0 :(得分:15)
创建自定义适配器并实现ViewHolder模式以维护List每个项目状态:
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;
}
}