簡體   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