我有一个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,但它无法正常工作。
答案 0 :(得分:0)
<LinearLayout
android:id="@+id/cotainer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"/>
</LinearLayout>
我通过从上到下改变来解决它。
<LinearLayout
android:id="@+id/cotainer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"/>
</LinearLayout>
yes.only TextView android:layout_width =&#34; match_parent&#34;到android:layout_width =&#34; wrap_content&#34;
答案 1 :(得分:0)
根据结果的外观,我猜框架不会更新&#34;再循环&#34;的高度。 TextView即使内容已更改。实际上它不会更新TextView正在使用的Layout对象。你能否尝试将TextView的layout_width设置为&#34; wrap_content&#34;?它将强制TextView重新计算(并重新创建)Layout对象。