如何将背景图像设置为按钮但是仍然像普通按钮一样工作(有效)?

问题描述 投票:0回答:3

当按钮已经设置了背景图像时,我一直在尝试实现Normal android按钮效果

但问题是,一旦设置了背景,按钮的默认性质就会消失(阴影,可点击的动画等......)

有人可以给我一个有效的解决方案吗?

这是我按钮的代码

<Button style="@style/Widget.AppCompat.Button.Colored"
        android:id="@+id/student"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/student"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintVertical_bias="0.891" />

它看起来很神奇,因为我已经设置了背景图像,但它仍然看起来你已经将图像设置为Java中的jLabel

如何在保持背景图像完整的同时获取默认按钮外观?

android android-button
3个回答
0
投票

按钮的工作原理是将背景设置为具有高程,阴影,波纹等的背景。要获得相同的行为,您需要将背景设置为执行涟漪效果并放置阴影和高程效果的StateListDrawable将您的图像作为所有内容的背景。您不能只将背景设置为图像,这将失去所有这些功能。实现这一目标的最简单方法是查看AOSP源代码并找到它使用的drawable,将其复制到您的项目中,并进行适当的编辑。

基本上在Android中,Button只是一个带有特殊背景预设的TextView。


0
投票

你为什么不使用ImageButton小部件?它具有与ButtonImageView相结合的相同行为

检查这个tutorial,看看如何使用它。

正如官方文件中所述

显示一个按钮,其中包含可由用户按下或单击的图像(而不是文本)。默认情况下,ImageButton看起来像常规Button,标准按钮背景在不同按钮状态下改变颜色。按钮表面上的图像由XML元素中的android:src属性或ImageView.setImageResource(int)方法定义


0
投票

案例1,效果显示在图像背后:

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?selectableItemBackground"
    android:src="@mipmap/desire_image" />

或椭圆形效果,但它仍然显示在图像后面

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?selectableItemBackgroundBorderless"
    android:src="@mipmap/desire_image" />

情况2,使用卡片视图包装图像和占位符视图,并设置单击占位符视图。效果将显示图像的正面:

<androidx.cardview.widget.CardView
        android:layout_width="wrap_content"
        app:cardCornerRadius="4dp"
        android:layout_height="wrap_content">

       <!-- Expect image view, image button, button-->
        <ImageView 
           android:layout_width="desire_size"
           android:layout_height="desire_size"
           android:src="@mipmap/desire_image" />

        <View
          android:id="@+id/clickable_view"
          android:layout_width="desire_size"
          android:layout_height="desire_size"
          android:background="?selectableItemBackground"/>

</androidx.cardview.widget.CardView>

注意:注册onClick事件以显示效果

© www.soinside.com 2019 - 2024. All rights reserved.