具有渐变轮廓的自定义按钮和具有透明背景的图标

如何解决具有渐变轮廓的自定义按钮和具有透明背景的图标

我正在尝试为我的Android应用程序创建自定义按钮。这些按钮仅用于在屏幕上添加/编辑/删除数据。但是,我想对按钮做一些漂亮的样式设置,但是我在android编程的工作方式上遇到了一些困难。

该想法是使边界具有给定厚度(例如2dp),其颜色为渐变色。但是,这意味着中心是透明的,我认为这是主要困难之一。与此同时,我希望按钮的内部有一个代表其功能的图标。

目前,我有这样的渐变及其圆形边缘:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="top">
        <shape android:shape="rectangle">
            <gradient
                android:startColor="@color/colorPrimaryDark"
                android:centerColor="@color/colorAccent"
                android:endColor="@android:color/white"
                android:angle="270" />
            <corners android:radius="20dp"/>
        </shape>
    </item>
</layer-list>

这对应于我想要的颜色。但是,在可绘制资源文件中似乎没有透明的中心。

与此问题有关,在我的代码中,我在ListView上方有一个LinearLayout,其中包含应最终应用此样式的三个按钮。但是,我什至无法更改按钮的背景颜色。

以下是代表活动的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AddPlayersActivity"
    android:orientation="vertical"
    android:paddingRight="10dp"
    android:paddingLeft="10dp"
    android:background="@drawable/background_gradient">

    <TextView
        android:id="@+id/add_players_activity_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:fontFamily="@font/lato_bold"
        android:text="@string/app_name"
        android:textAlignment="center"
        android:textColor="@android:color/white"
        android:textSize="36sp" />

    <TextView
        android:layout_below="@+id/add_players_activity_title"
        android:id="@+id/add_players_activity_current_players"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lato"
        android:text="@string/current_players"
        android:textColor="@android:color/white"
        android:textSize="20sp" />

    <ListView
        android:id="@+id/add_players_activity_player_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/add_players_activity_current_players"
        android:layout_above="@id/add_players_activity_button_layout" />

    <LinearLayout
        android:id="@+id/add_players_activity_button_layout"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginHorizontal="10dp"
            android:text="Add"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginHorizontal="10dp"
            android:text="Edit"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginHorizontal="10dp"
            android:text="Delete" />
    </LinearLayout>
</RelativeLayout>

其他StackOverflow问题都没有解决我的任何一个问题。甚至是最常见的“设置按钮的style属性”。

我对可能需要外部工具或其他东西的解决方案持开放态度,因此不会局限于内部功能。不过,我确实认为Android Studio中必须有解决此问题的方法。

在此先感谢所有需要时间调查的人!

这里是一个要求的示例(唯一的区别是我将使用可绘制/图像而不是文本)

Example

解决方法

我不知道这是否是最佳解决方案,但是您可以通过以下方式轻松实现:

  1. 创建gradient_back.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="10dp" />
    <gradient
        android:endColor="@color/colorPrimary"
        android:startColor="@color/colorAccent" />
</shape>
  1. 创建shape_front.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="9dp" />
    <solid android:color="@android:color/white" />
</shape>
  1. 现在在您的布局中创建一个如下所示的按钮:
<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient_back">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:background="@drawable/shape_front"
        android:text="WOW" />

</FrameLayout>

结果:

enter image description here


具有透明主体但不具有渐变的版本:

  1. 向您的build.gradle(模块:应用)添加:
implementation "com.google.android.material:material:1.2.1"
  1. res/values/styles中将父样式更改为:
parent="Theme.MaterialComponents.Light.DarkActionBar"
  1. 现在在布局中您可以添加一个按钮:
<com.google.android.material.button.MaterialButton
    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="WOW"
    android:textColor="@color/textColor"
    app:cornerRadius="10dp"
    app:strokeWidth="2dp"
    app:strokeColor="@color/colorAccent" />

结果:

enter image description here

,

我建议为此创建一个自定义视图。创建自定义视图对您非常有益,因为您已经提到了许多按钮。通过自定义视图,您可以重复使用具有不同高度,宽度,边框宽度,颜色和拐角半径的按钮。

阅读更多自定义视图here。您还可以通过一系列this one开始的代码实验室。

attrs.xml (值/attrs.xml):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Custom attributes for the button -->
    <declare-styleable name="StyledButton">
        <attr name="cornerRadius" format="dimension" />
        <attr name="borderWidth" format="dimension" />
        <attr name="startColor" format="color" />
        <attr name="centerColor" format="color" />
        <attr name="endColor" format="color" />
    </declare-styleable>
</resources>

StyledButton.kt

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Shader
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageButton
import androidx.core.content.withStyledAttributes

class StyledButton @JvmOverloads constructor(
    context: Context,attrs: AttributeSet? = null,defStyleAttr: Int = 0
) : AppCompatImageButton(context,attrs,defStyleAttr) {

    private var cornerRadius = 0f
    private var borderWidth = 0f
    private var startColor = 0
    private var centerColor = 0
    private var endColor = 0

    private val path = Path()
    private val borderPaint = Paint().apply {
        style = Paint.Style.FILL
    }

    init {
        //Get the values you set in xml
        context.withStyledAttributes(attrs,R.styleable.StyledButton) {
            borderWidth = getDimension(R.styleable.StyledButton_borderWidth,10f)
            cornerRadius = getDimension(R.styleable.StyledButton_cornerRadius,10f)
            startColor = getColor(R.styleable.StyledButton_startColor,Color.WHITE)
            centerColor = getColor(R.styleable.StyledButton_centerColor,Color.RED)
            endColor = getColor(R.styleable.StyledButton_endColor,Color.BLACK)
        }
    }

    override fun onSizeChanged(w: Int,h: Int,oldw: Int,oldh: Int) {
        super.onSizeChanged(w,h,oldw,oldh)

        // Create and set your gradient here so that the gradient size is always correct
        borderPaint.shader = LinearGradient(
            0f,0f,width.toFloat(),height.toFloat(),intArrayOf(startColor,centerColor,endColor),null,Shader.TileMode.CLAMP
        )
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        //Remove inner section (that you require to be transparent) from canvas
        path.rewind()
        path.addRoundRect(
            borderWidth,borderWidth,width.toFloat() - borderWidth,height.toFloat() - borderWidth,cornerRadius - borderWidth / 2,Path.Direction.CCW
        )
        canvas.clipOutPath(path)

        //Draw gradient on the outer section
        path.rewind()
        path.addRoundRect(
            0f,cornerRadius,Path.Direction.CCW
        )
        canvas.drawPath(path,borderPaint)
    }
}

用法

<com.example.andriod.myapplication.StyledButton
    android:layout_width="100dp"
    android:layout_height="40dp"
    android:src="@drawable/ic_android"
    android:scaleType="center"
    android:layout_gravity="center"
    app:borderWidth="2dp"
    app:cornerRadius="20dp"
    app:startColor="@color/colorPrimaryDark"
    app:centerColor="@android:color/holo_red_dark"
    app:endColor="@color/colorPrimary"/>

结果

Styled button result

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-