how can i add a viewview to a button contained within a grid layout?

You could stack an ImageView with the “X” vector as its image on top of the button and change its visibility once the button is clicked using an OnClickListener. Here is a simple example:

Layout:

<Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

<ImageView
    android:elevation="10dp"
    android:id="@+id/iv_cross"
    android:src="@drawable/ic_clear_24px"
    android:visibility="invisible"
    android:layout_width="50dp"
    android:layout_height="50dp"
    app:layout_constraintTop_toTopOf="@id/btn"
    app:layout_constraintBottom_toBottomOf="@id/btn"
    app:layout_constraintLeft_toLeftOf="@id/btn"
    app:layout_constraintRight_toRightOf="@id/btn"/>

Where “@drawable/ic_clear_24px” is the “X” vector.

Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = findViewById(R.id.btn);
    final ImageView iv_cross = findViewById(R.id.iv_cross);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            iv_cross.setVisibility(View.VISIBLE);
        }
    });
}

Note that the visibility of the ImageView is set to invisible by default.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top