You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中自定义LinearLayout实现带徽章的通用头像组件

Custom Avatar LinearLayout Component Implementation

Got it! Let's turn that reusable avatar layout into a custom LinearLayout component that's easy to maintain and use across your project. Here's a step-by-step implementation:

1. Create the Reusable Layout File

First, move your existing avatar layout into a standalone layout file (res/layout/custom_avatar_view.xml):

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

    <com.makeramen.roundedimageview.RoundedImageView
        android:id="@+id/iv_profile_pic"
        style="@style/ImageViewStyle"
        android:layout_width="@dimen/size_profilepic_menu"
        android:layout_height="@dimen/size_profilepic_menu"
        android:layout_gravity="center"
        android:src="@drawable/ic_user_default"
        app:riv_border_color="@color/orange_dark"
        app:riv_border_width="1dp"
        app:riv_corner_radius="@dimen/size_profilepic_menu"
        app:riv_oval="true" />

    <ImageView
        android:id="@+id/iv_profile_badge"
        android:layout_width="30dp"
        android:layout_height="18dp"
        android:layout_marginLeft="@dimen/_minus2sdp"
        android:layout_marginTop="@dimen/_minus5sdp"
        android:rotation="335"
        app:srcCompat="@drawable/ic_pro_crown_yelloworange" />

</LinearLayout>

2. Build the Custom View Class

Create a CustomAvatarView class that extends LinearLayout. This class will handle image loading, badge visibility, and any customizations you need:

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.bumptech.glide.Glide
import com.makeramen.roundedimageview.RoundedImageView
import kotlinx.android.synthetic.main.custom_avatar_view.view.*

class CustomAvatarView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private val profilePic: RoundedImageView by lazy { iv_profile_pic }
    private val profileBadge: androidx.appcompat.widget.AppCompatImageView by lazy { iv_profile_badge }

    init {
        // Inflate our custom layout into this LinearLayout
        LayoutInflater.from(context).inflate(R.layout.custom_avatar_view, this, true)
        
        // Optional: Handle XML attributes for easy configuration
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.CustomAvatarView, defStyleAttr, 0)
            
            // Set badge visibility from XML
            val showBadge = typedArray.getBoolean(R.styleable.CustomAvatarView_showBadge, true)
            setBadgeVisibility(showBadge)
            
            // Set border color from XML
            val borderColor = typedArray.getColor(R.styleable.CustomAvatarView_borderColor, context.getColor(R.color.orange_dark))
            profilePic.borderColor = borderColor
            
            typedArray.recycle()
        }
    }

    /**
     * Load a remote avatar image using Glide
     * @param url: Remote image URL
     * @param placeholderRes: Optional placeholder for loading state
     */
    fun setAvatarUrl(url: String, placeholderRes: Int = R.drawable.ic_user_default) {
        Glide.with(context)
            .load(url)
            .placeholder(placeholderRes)
            .circleCrop() // Matches the oval shape of RoundedImageView
            .into(profilePic)
    }

    /**
     * Toggle visibility of the profile badge
     */
    fun setBadgeVisibility(isVisible: Boolean) {
        profileBadge.visibility = if (isVisible) VISIBLE else GONE
    }

    /**
     * Update the badge drawable
     */
    fun setBadgeDrawable(drawableRes: Int) {
        profileBadge.setImageResource(drawableRes)
    }

    // Add more methods here for extra customizations (border width, corner radius, etc.)
}

3. Add Custom XML Attributes (Optional but Useful)

If you want to configure the view directly from XML, add these attributes to res/values/attrs.xml:

<resources>
    <declare-styleable name="CustomAvatarView">
        <attr name="showBadge" format="boolean" />
        <attr name="borderColor" format="color" />
        <attr name="avatarSize" format="dimension" />
        <!-- Add any other configurable attributes you need -->
    </declare-styleable>
</resources>

4. Use the Custom View Everywhere

Now you can drop this component into any layout in your project with minimal code:

XML Usage

<com.yourpackage.name.CustomAvatarView
    android:id="@+id/user_avatar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:showBadge="true"
    app:borderColor="@color/orange_dark" />

Kotlin Usage

// Load a remote avatar
val userAvatar = findViewById<CustomAvatarView>(R.id.user_avatar)
userAvatar.setAvatarUrl("https://your-domain.com/user-profile.jpg")

// Hide the badge if needed
userAvatar.setBadgeVisibility(false)

// Change the badge icon
userAvatar.setBadgeDrawable(R.drawable.ic_new_premium_badge)

Quick Notes

  • Make sure you have Glide (or your preferred image loader) added to your app-level build.gradle dependencies.
  • The RoundedImageView dependency should already be in your project since you're using it in the original layout.
  • You can extend this class further to add error handling for image loads, click listeners, or badge animations.

内容的提问来源于stack exchange,提问作者Jatin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:20:41