Android 中 Button 的基本使用
-
- 1. 文字大小颜色
- 2. 自定义背景形状
- 3. 自定义按压效果
- 4. 点击事件
1. 文字大小颜色
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="15dp" android:orientation="vertical" tools:context=".ButtonActivity"> <Button android:id="@+id/btn_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/button" android:textSize="25sp" android:textColor="@color/teal_200" android:background="@color/black"/> </LinearLayout>
使背景颜色生效: 改动
themes.xml
文件. 夜间的看情况改动.
Theme.MaterialComponents.DayNight.DarkActionBar.Bridge
2. 自定义背景形状
文件内容为:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/orange_low" /> <corners android:radius="15dp" /> </shape>
<Button android:id="@+id/btn_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/button" android:textSize="25sp" android:textColor="@color/red" android:layout_margin="15dp" android:background="@drawable/bg_btn2"/>
描边
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:width="1dp" android:color="@color/red" /> <corners android:radius="15dp" /> </shape>
3. 自定义按压效果
建立一个 drawable 文件
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <shape android:shape="rectangle"> <corners android:radius="15dp" /> <solid android:color="@color/yellow_blew" /> </shape> </item> <item android:state_pressed="false"> <shape android:shape="rectangle"> <corners android:radius="10dp" /> <solid android:color="@color/blue" /> </shape> </item> </selector>
<Button android:id="@+id/btn_4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/button" android:textSize="25sp" android:textColor="@color/white" android:layout_margin="15dp" android:background="@drawable/bg_btn4"/>
4. 点击事件
添加一个属性, showToast 为方法名.
android:onClick="showToast"
在对应的 Activity 建立一个函数.
public void showToast(View view) { // 提示信息 Toast.LENGTH_SHORT 短时间, Toast.LENGTH_LONG 长时间 Toast.makeText(this, "一个点击事件", Toast.LENGTH_SHORT).show(); }
点击事件不是 Button 也可以设置.
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/889945.html