-1

I would like to create custom component in Android Studio. This should be a button but with other components like ImageView or ChceckBox inside. How to do this?

I'm already tried create a Compound Control (LinearView with components inside) but I can't set onClickListener to catch click event of this and it's not so elegant solution.

I would like to avoid creating my own component nearly from scratch (extend View and override onDraw method) but I don't know how I can do this in other way.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Moses
  • 5
  • 2
  • 1
    "I can't set onClickListener to catch click event of this" -- why not? `setOnClickListener()` exists, and it works. You do need to mark the container as being clickable (e.g., `android:clickable="true"` in a layout). – CommonsWare May 14 '19 at 21:33

1 Answers1

1

You can use ConstraintLayout to achieve view over/inside another view, something like this:

?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:scaleType="fitXY"
    tools:srcCompat="@tools:sample/avatars[10]" />

<CheckBox
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:text="check"
    app:layout_constraintBottom_toBottomOf="@+id/imageView"
    app:layout_constraintEnd_toEndOf="@+id/imageView"
    app:layout_constraintStart_toStartOf="@+id/imageView"
    app:layout_constraintTop_toTopOf="@+id/imageView" />

</android.support.constraint.ConstraintLayout>

This will look like this:

enter image description here

And about your click listeners - if you want to do the same thing when any of your views are clicked just add a click listener to your parent layout.

If you want to do different things for different view clicks with ConstraintLayout you can simply attach click listener for every view that you have.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53