Search code examples
androidimageandroid-gridviewcustom-view

Can you create a custom view?


I am trying to recreate a screen from one application (see picture). The problem I am facing is focused on the grid elements of the screen. Is it possible to create a custom view which is a combination of an image and a text view (like in the picture) or should I add the image view and text views separately in each row of the grid view?

two muppets


Solution

  • step 1 :

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="134dp"
        android:layout_height="154dp"
        android:background="@drawable/grey_rounded_background"
        android:gravity="center"
        android:padding="16dp">
    
        <ImageView
            android:id="@+id/image"
            android:layout_width="80dp"
            android:layout_height="70dp"
            android:layout_marginBottom="8dp"
            tools:src="@color/colorPrimary" />
    
        <TextView
            android:id="@+id/caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:text="Caption of the Image"
            android:textAlignment="center"
            android:textColor="#666"
            android:textSize="12sp"/>
    
    </LinearLayout>
    

    step 2

    <declare-styleable name="BenefitView">
        <attr name="image" format="reference"/>
        <attr name="text" format="string"/>
    </declare-styleable>
    

    step 3

    class BenefitView(context: Context, attrs: AttributeSet): LinearLayout(context, attrs) {
    
        init {
            inflate(context, R.layout.benefit_view, this)
    
            val imageView: ImageView = findViewById(R.id.image)
            val textView: TextView = findViewById(R.id.caption)
    
            val attributes = context.obtainStyledAttributes(attrs, R.styleable.BenefitView)
            imageView.setImageDrawable(attributes.getDrawable(R.styleable.BenefitView_image))
            textView.text = attributes.getString(R.styleable.BenefitView_text)
            attributes.recycle()
    
        }
    }
    

    use :

    <com.iacovelli.customview.BenefitView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          app:text="Apply and chat with our hosts"
          app:image="@drawable/first_image"
          android:layout_marginEnd="12dp"/>