首页 > 解决方案 > 在 ImageButton 上设置前景和背景图像并通过 ID 访问它们

问题描述

我想创建一个按钮。在 XML 代码中选择了谁的默认图像

现在,当活动开始时,我使用给定的 JAVA 代码从按钮背景中的多个图像中设置随机图像

我的问题是我想在用户单击按钮时显示背景图像(与使用下面的 JAVA 代码随机设置的相同)。如何通过 id 访问背景图像和通过 id 访问前景图像,以及 onClick 事件我显示背景图像并隐藏前景?如果可以怎么办????

感谢帮助!

        android:id="@+id/imageButton_0"
        android:tag="imageButton_0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/emoji" />


                // JAVA code

                int randomPosition = new Random().nextInt(positionArray.length - count);

                String str = "imageButton_" + Integer.toString(positionArray[randomPosition]);
                Log.v(TAG, str);
                ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.my_game_board);
                ImageButton btn = constraintLayout.findViewWithTag(str);
                btn.setBackgroundResource(imagesArray[i]);```

标签: androidandroid-imagebutton

解决方案


推荐阅读