在ImageButton上设置前景和背景图像,并通过ID

时间:2020-01-11 10:27:16

标签: android android-imagebutton

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

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

我的问题是我想显示用户单击按钮时的背景图像(使用下面的JAVA代码随机设置的背景图像)。 如何通过ID访问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]);```

0 个答案:

没有答案