android - 如何设置 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" />
解决方案
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
)
推荐阅读
- android - Firebase 应用程序检查在 android 上破坏应用程序
- elasticsearch - ElasticSearch Nest 客户端 Ver 7.13 - Id 字段值未设置为 _id 字段值
- json - 如何在 React 中使用 useState、useEffect 和 axios auth 映射 json 对象?
- windows - 如何使用批处理文件查找包含括号的文件
- r - 重新排序 ggplot2 中的图形
- python - Python pandas datareader 0.4.1 在 daily.py 中添加标题
- c# - 如果捕获到特定异常,则返回到引发异常的行下方的代码
- browser - 会话存储是否会在浏览器版本更新时消失?
- r - 如何绘制已经计算的分布?
- python - 我的函数在重复时会重置值。有没有办法解决这个问题?