簡體   English   中英

嘗試設置 imageView 的寬度以匹配 TextView 的寬度

[英]Trying to set the width of an imageView to match the width of a TextView

我正在嘗試聊天,我希望每條消息都有一個與文本大小匹配的背景圖像。

這是我的 xml:

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/msgBg"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_textsms_black_24dp"
        >

    </ImageView>

    <TextView
        android:id="@+id/textMSG"
        android:layout_alignParentStart="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:layout_marginLeft="@dimen/margin_big"
        android:text="example"
        android:layout_weight="70"
        android:textSize="@dimen/text_size_bigmedium"
        >

    </TextView>

</RelativeLayout>

我的聊天 kt 適配器:

class ChatAdapter(var list :ArrayList<ChatMessage>):RecyclerView.Adapter<ChatAdapter.ViewHolder>(){

    class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        val image = itemView.Profile
        val text = itemView.textMSG
        var bg = itemView.msgBg
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(com.example.gamecompanionAleixAzuela.R.layout.item_chat, parent, false)

        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return list.count();
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.text.text = list[position].text
        holder.bg.layoutParams.width = holder.text.measuredWidth;
        holder.bg.layoutParams.height = holder.text.measuredHeight;
    }
}

如您所見,我將 bg 寬度設置為文本的測量寬度,但它不起作用,因為尚未測量視圖。 我不知道如何修復它,因為我沒有確定數量的消息,所以我無法在創建視圖時執行

如果你想使用imageView作為背景,這是錯誤的,你可以像這樣在你的relativeLayout使用background

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ic_textsms_black_24dp"
>

    <TextView
        android:id="@+id/textMSG"
        android:layout_alignParentStart="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:layout_marginLeft="@dimen/margin_big"
        android:text="example"
        android:layout_weight="70"
        android:textSize="@dimen/text_size_bigmedium"
        >

    </TextView>

</RelativeLayout>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM