HarmonyOS鸿蒙Next中button选中状态和normal状态图片怎么设置
HarmonyOS鸿蒙Next中button选中状态和normal状态图片怎么设置
button normal状态一张图片 selected状态一张图片
@Entry @Component struct Page240605153407040 { @State message: string = ‘app.media.photo’;
build() { Row() { Column() { Button() { Image($r(this.message)) } .width(40).height(40).margin({ left: 18 }) .onClick(=>{ if (this.message == ‘app.media.photo’ ) { this.message = ‘app.media.startIcon’ } else { this.message = ‘app.media.photo’ }
})
}
.width('100%')
}
.height('100%')
} }
更多关于HarmonyOS鸿蒙Next中button选中状态和normal状态图片怎么设置的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,设置Button的选中状态和普通状态的图片可以通过XML布局文件和代码实现。首先,在resources/base/media目录下准备好两张图片,例如normal_image.png和selected_image.png。然后在XML布局文件中,使用Button组件,并通过background属性设置普通状态的图片,通过state_selected属性设置选中状态的图片。示例代码如下:
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/normal_image"
android:state_selected="false" />
在Java或Kotlin代码中,可以通过setSelected方法动态切换Button的选中状态:
Button myButton = findViewById(R.id.my_button);
myButton.setSelected(true); // 设置为选中状态
myButton.setSelected(false); // 设置为普通状态
此外,还可以使用StateListDrawable来实现不同状态下的图片切换。在resources/base/drawable目录下创建一个XML文件,例如button_states.xml,内容如下:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/selected_image" />
<item android:state_selected="false" android:drawable="@drawable/normal_image" />
</selector>
然后在XML布局文件中引用这个StateListDrawable:
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_states" />
这样,Button在选中状态和普通状态下会自动切换对应的图片。
在HarmonyOS鸿蒙Next中,可以通过XML布局文件或Java/Kotlin代码设置Button的选中和正常状态图片。使用XML时,定义selector资源文件,指定state_pressed和默认状态对应的图片,然后在Button的background属性中引用该selector。例如:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/button_pressed" />
<item android:drawable="@drawable/button_normal" />
</selector>
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_selector" />
在代码中,可以使用setBackgroundResource()方法动态设置selector资源。

