我有一个ListView
,项目是一个TextView
。当我只使用字符串时效果很好。TextView
添加时布局错误ImageSpan
。跟随是我的代码。初始化一个列表视图
private void initListView()
{
SpannableString spannableString1 = replaceEmotion(this, "[Android]", 0);
SpannableString spannableString2 = replaceEmotion(this, "123456123456123456", 0);
for (int i = 0; i < 140; i++)
{
int t = (int) (Math.random() * 2);
if (t % 2 == 0)
{
listData.add(spannableString1);
}
else
{
listData.add(spannableString2);
}
}
listItemAdapter = new ArrayAdapter<>(this, R.layout.item_list, listData);
}
将字符串替换为 ImageSpan。
public SpannableString replaceEmotion(Context context, String content, int length)
{
if (length < 0)
{
length = 0;
}
SpannableString result = new SpannableString(content);
if (context == null || content == null)
{
return null;
}
int start = length;
int end;
while ((start = content.indexOf("[", start)) != -1 && (end = content.indexOf("]", start)) != -1)
{
String img = content.substring(start, end + 1);
if ("[Android]".equals(img))
{
Drawable drawable = context.getResources().getDrawable(R.mipmap.ic_launcher);
if (drawable != null)
{
drawable.setBounds(0, 0, (int) context.getResources().getDimension(R.dimen.fab_margin) * 3,
(int) context.getResources().getDimension(R.dimen.fab_margin) * 3);
ImageSpan span = new ImageSpan(drawable);
result.setSpan(span, start, end + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
start++;
}
return result;
}
我曾尝试 requestLayout,但它不起作用。