我正在实现一个应用程序,显示从 .net 服务器获得的图像和消息。为此,我要添加 LinearLayout
与 TextView
和 ImageView
动态地使用 for 循环。
起初我收到消息并将它们添加到 TextView
虚拟图像放置在 ImageView
:
for(int i = 0; i < messages.size(); i++) {
FrameLayout f1 = new FrameLayout(this);
LinearLayout l1 = new LinearLayout(this);
LinearLayout l2 = new LinearLayout(this);
im = new ImageView(this);
TextView tv = new TextView(this);
tv.setText(messages.get(i).getmessage());
im.setImageResource(R.drawable.person);
l1.addView(tv);
l2.addView(im);
f1.addView(l1);
f1.addView(l2);
((LinearLayout)findViewById(R.id.LinearlayoutMessage)).addView(f1);
}
一段时间后,我得到了原始图像。我的目的是用原始图像替换虚拟图像。为了实现这一点,我正在使用
imageview.getid()
不幸的是,我得到了 imageview 的最后一个 id。但我需要获取每个单独的 ImageView ID。用真实图像更改虚拟图像的最佳方法是什么?
最佳答案
看起来您需要将每个 imageView id 存储在每个消息的 map 中 -> imageView 像这样:
Map<Message, Long> messageMapping = new HashMap<Message, Long>();
for(int i = 0; i < messages.size(); i++) {
FrameLayout f1 = new FrameLayout(this);
LinearLayout l1 = new LinearLayout(this);
LinearLayout l2 = new LinearLayout(this);
im = new ImageView(this);
TextView tv = new TextView(this);
//add mapping
messageMapping.put(messages.get(i), im.getId());
tv.setText(messages.get(i).getmessage());
im.setImageResource(R.drawable.person);
l1.addView(tv);
l2.addView(im);
f1.addView(l1);
f1.addView(l2);
((LinearLayout)findViewById(R.id.LinearlayoutMessage)).addView(f1);
}
然后,当需要将图像延迟加载到现有 imageViews 时,您只需通过消息映射查找 imageView id 引用:
(完全猜测您的代码可能是什么样子)
for(int i = 0; i < messages.size(); i++){
Image image = queryServerForImage(messages.get(i).getImageId());
ImageView imageView = ((ImageView)findViewById(messageMapping.get(messages.get(i))));
//some conversion & seteup may be needed to get image into proper format
imageView.setImageBitmap(image);
}
您可以对异步任务执行类似的操作。您可以将消息 ImageView 创建循环中的每一个与关联的资源 id 相结合,并让每个 asyc 任务从网络响应更新 ui。
关于android-imageview - 在 Android 中获取 ImageView 的 id 有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7397146/