📅  最后修改于: 2023-12-03 15:07:51.845000             🧑  作者: Mango
在Android应用开发中,我们经常需要使用按钮来完成交互操作。为了使应用界面更加美观、一致,Google所推出的材料设计风格的按钮已成为Android应用界面设计的标准。
在材料设计中,按钮的主题可以分为基础样式、扁平样式、浮动样式、描边样式、圆形样式等。本文将通过示例介绍如何在Android中进行材料设计按钮的主题设置。
基础样式的按钮是最常见的按钮样式,其颜色和形状都是较为简单的。
在布局文件中定义一个基础样式的按钮:
<Button
android:id="@+id/basic_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Basic Button" />
在代码中可以对该按钮进行背景色设置:
Button basicButton = findViewById(R.id.basic_button);
basicButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
结果如下图所示:
扁平样式的按钮与基础样式的按钮类似,其特点是没有浮起的阴影效果,只有底色和字体颜色。
在布局文件中定义一个扁平样式的按钮:
<Button
android:id="@+id/flat_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flat Button" />
在代码中可以对该按钮进行背景色和字体颜色设置:
Button flatButton = findViewById(R.id.flat_button);
flatButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
flatButton.setTextColor(getResources().getColor(R.color.colorAccent));
结果如下图所示:
浮动样式的按钮会带有阴影效果,其颜色和形状与基础样式的按钮相似。
在布局文件中定义一个浮动样式的按钮:
<Button
android:id="@+id/float_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Float Button" />
在代码中可以对该按钮进行背景色设置:
Button floatButton = findViewById(R.id.float_button);
floatButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
结果如下图所示:
描边样式的按钮与基础样式的按钮类似,但其边框不同。
在布局文件中定义一个描边样式的按钮:
<Button
android:id="@+id/outline_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Outline Button"
android:textColor="@color/colorPrimary"
android:background="@drawable/border_button" />
在drawable文件夹下定义一个形状文件border_button.xml作为边框。
border_button.xml的内容如下:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="2dp"
android:color="@color/colorPrimary" />
<corners
android:radius="20dp" />
</shape>
在代码中无需设置背景色,因为描边样式的按钮通过形状文件的边框颜色来进行区分。
结果如下图所示:
圆形样式的按钮是一种特殊样式的按钮,其形状为圆形,通常用于需要突出的按钮。
在布局文件中定义一个圆形样式的按钮:
<Button
android:id="@+id/circle_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Circle Button"
android:textColor="@android:color/white"
android:background="@drawable/circle_button" />
在drawable文件夹下定义一个形状文件circle_button.xml作为背景。
circle_button.xml的内容如下:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thickness="20dp">
<solid android:color="@color/colorPrimary" />
</shape>
在代码中无需设置背景色,因为圆形样式的按钮通过形状文件的填充色来进行区分。
结果如下图所示:
以上就是对Android中材料设计按钮的主题设置的介绍和示例。
(以上内容已按markdown格式编辑,可直接复制粘贴使用)