首页 > 解决方案 > 如何设置 ImageButton 的可见性

问题描述

我有一个 ImageButton,我想根据用户手机上闪存的可用性删除它。我只是坚持在 Kotlin 中设置可见性。

这是我的代码:

private fun checkForFlashAvailability() {
  try {
    val isFlashAvailable = camera?.cameraInfo?.hasFlashUnit() ? : false

    //SOMETHING HERE TO SET VISIBILITY 

  } catch (e: CameraInfoUnavailableException) {
    Logger.warning(TAG, "Cannot get flash available information: ${e.message}")
  }
}

我知道它必须遵循与此类似的代码结构:

bottomAppBar.menu.findItem(R.id.menu_flash).isVisible = isFlashAvailable

这是 XML:

        <ImageButton
            android:id="@+id/flash_button"
            android:layout_width="43dp"
            android:layout_height="43dp"
            android:layout_marginEnd="@dimen/margin_xlarge"
            android:layout_marginBottom="@dimen/margin_xlarge"
            android:background="@android:color/transparent"
            android:clickable="true"
            android:contentDescription="@string/switch_camera_button_alt"
            android:focusable="true"
            android:padding="@dimen/spacing_small"
            android:scaleType="fitCenter"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:srcCompat="@drawable/ic_flash_off" />

标签: androidkotlin

解决方案


ImageView继承自View,因此它确实有一个功能setVisibility(visibility: Int),您可以使用它来设置其可见性。

有 3 种类型的可见性可用。

  • View.VISIBLE - 这个视图是可见的。
  • View.INVISIBLE - 这个视图是不可见的,但它仍然占用空间用于布局。
  • View.GONE - 此视图是不可见的,并且它不占用任何空间用于布局目的。

设置可见性的示例:

val isFlashAvailable = camera?.cameraInfo?.hasFlashUnit() ?: false

val view: ImageView = findViewById(R.id.flash_button)
view.setVisibility(
    // Using GONE since we won't need it, CameraInfo.hasFlashUnit() will never change.
    if (isFlashVisible) View.VISIBLE else View.GONE
)

推荐阅读