Android开发学习教程(6)- Android Button用法和属性
—— 真正的勇士,敢于直面惨淡的人生。 ——鲁讯
Button是什么
Button按钮,是用户交互中使用最多的组件,在很多应用程序中都很常见。当用户单击按钮的时候,会有相对应的响应动作。
Button有什么用
用来响应用户点击事件,常用的有登录按钮、注册按钮、拨打电话按钮等等。
Button的使用
以上一篇章中的TextView项目为例,我们先把TextView改为距离顶部40dp,下面添加一个Button的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
androidx.constraintlayout.widget.ConstraintLayout
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
=
".TestActivity"
>
<
TextView
android:id
=
"@+id/textView"
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
android:layout_marginTop
=
"40dp"
android:background
=
"#cccccc"
android:singleLine
=
"true"
android:text
=
"Hello Activity Hello Activity Hello Activity Hello Activity"
android:textColor
=
"#FF0000"
android:textSize
=
"20sp"
app:layout_constraintEnd_toEndOf
=
"parent"
app:layout_constraintHorizontal_bias
=
"0.0"
app:layout_constraintStart_toStartOf
=
"parent"
app:layout_constraintTop_toTopOf
=
"parent"
/>
<
Button
android:id
=
"@+id/button"
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
android:text
=
"Button"
app:layout_constraintEnd_toEndOf
=
"parent"
app:layout_constraintStart_toStartOf
=
"parent"
app:layout_constraintTop_toBottomOf
=
"@+id/textView"
android:layout_marginTop
=
"20dp"
/>
</
androidx.constraintlayout.widget.ConstraintLayout
>
Button属性
1
2
3
4
5
6
7
8
android:text:按钮上显示的文字内容;
android:layout_width:Button的宽度(或者说长度),值为wrap_content意思是自适应宽度,就是Button上的文字有多长,Button的宽度就有多长;
android:layout_width:Button的高度,值为wrap_content意思是自适应高度,就是Button的文字有多高,Button的高度就有多高;
android:layout_marginTop:控件顶部离上方的距离;
app:layout_constraintEnd_toEndOf=
"parent"
:表示Button的右边与父类控件(也就是ConstraintLayout)的右边对齐;
app:layout_constraintStart_toStartOf=
"parent"
:表示Button的左边与父类控件(也就是ConstraintLayout)的左边对齐;
app:layout_constraintTop_toBottomOf=
"@+id/textView"
:表示Button的顶部与textView控件的底部对齐;
app:layout_marginTop=
"20dp"
:表示Button的顶部距离textView控件的底部20dp;
按钮的点击事件
同样,Button和上一篇章中的TextView一样,还有颜色、字体大小、背景颜色等属性,同学们可以自己去试试效果,这里主要要讲的是按钮的点击事件,也就是用户点击了按钮之后会发生什么事件。基于以上项目,在TestActivity设置按钮的点击事件并弹出提示“我被点击了”:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import
android.os.Bundle;
import
android.view.View;
import
android.widget.Button;
import
android.widget.Toast;
public
class
TestActivity
extends
AppCompatActivity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Button button = findViewById(R.id.button);
button.setOnClickListener(
new
View.OnClickListener() {
@Override
public
void
onClick(View v) {
Toast.makeText(TestActivity.
this
,
"我被点击了"
, Toast.LENGTH_SHORT).show();
}
});
}
}
下一篇章我们讲讲Button点击事件的原理
源码链接:https://yunjunet.cn/876730.html