繁体   English   中英

如何在Android中将TextView / ImageView动态添加到ListView项

[英]How to dynamically add a TextView/ImageView to a ListView item in Android

我正在用Android创建聊天应用程序。 我能够使用以下作为列表项布局来创建普通文本聊天列表视图:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<TextView
    android:id="@+id/chat_msg_view"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"/>

<TextView
    android:id="@+id/msg_send_time"
    android:layout_width="250dp"
    android:layout_height="20dp"
    android:layout_below="@+id/chat_msg_view"
    android:layout_margin="2dp"
    android:paddingTop="2dp"
    android:textColor="@android:color/holo_blue_dark" />
<TextView
    android:id="@+id/msg_status"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/msg_send_time"
    android:layout_margin="2dp"
    android:paddingTop="2dp"
    android:textColor="@android:color/holo_blue_dark" />
</RelativeLayout>

但是现在我正尝试通过聊天发送图像。 所以现在如果要发送的内容是IMAGE,则需要将上述布局中的第一个TextView替换为ImageView。

有什么好的方法可以做到这一点。

您可以使用多种方法。 如果使用列表视图适配器,则可以使用itemType更改整个列表项的布局(如果要更改整个布局,则很好,但是可能有点复杂),也可以将图像视图放置在布局中的同一位置作为文本视图,显示或隐藏您正在使用的那个。 IE如果显示图像,则显示图像视图并隐藏文本视图;如果显示的是文本视图,则显示文本并隐藏图像。 然后,您无需在运行时插入/删除视图,这会稍微复杂一些。

您的布局可能看起来像这样...

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<TextView
    android:id="@+id/chat_msg_view"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"/>

<ImageView
    android:id="@+id/chat_image_view"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:visibility="gone"/>

<TextView
    android:id="@+id/msg_send_time"
    android:layout_width="250dp"
    android:layout_height="20dp"
    android:layout_below="@+id/chat_msg_view"
    android:layout_margin="2dp"
    android:paddingTop="2dp"
    android:textColor="@android:color/holo_blue_dark" />
<TextView
    android:id="@+id/msg_status"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/msg_send_time"
    android:layout_margin="2dp"
    android:paddingTop="2dp"
    android:textColor="@android:color/holo_blue_dark" />
</RelativeLayout>

请注意chat_image_view也是如何与父对象左对齐的。它位于文本视图的顶部 ,但可见性“消失”,因此您将看不到它。

希望这有帮助,祝你好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM