安卓开发教程14:Button按钮详解(上)

106 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第14天,点击查看活动详情

今天我们来说Android中的按钮 Button,这个控件可以说是必须要掌握的,因为我们的程序要与用户产生交互效果都需要用户的点击或者触摸行为,那么按钮就是首当其中的一个控件。

Button按钮其实是继承自TextView,所以TextView的大多数属性按钮都可以直接使用,但是有些不同的地方。

Button与TextView中的不同:

  1. Button中的文字默认是自动居中显示,而TextView中的文字默认是靠左显示。
  2. Button中的英文默认强制大写,而TextView的文字默认不强制大写。(Button中需要设置textAllCaps="false"来取消英文强制大写)
  3. Button中的background需要编写一个drawable资源文件来使用,默认带背景颜色;而TextView可直接设置颜色,默认无背景颜色。
  4. Button默认有点击效果,而TextView默认无点击效果。
  5. Button会拦截点击事件,而TextView默认是不会拦截点击事件的。

示例:

下面让我们来写一个拥有一个Button 控件,和一个TextView控件,线性垂直排列的实例看一下。

<Button
    android:id="@+id/bt_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/buttonText"/>

<TextView
    android:id="@+id/tv_text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/textTest"/>

image.png

按钮点击事件:

按钮肯定是用来与用户产生交互的,那么首当其冲的就是按钮的点击事件。 如果有前端基础的话,就会知道网页中的点击事件,可以在html的标签中添加onclick 来添加点击事件的,那么Android中一样我们也可以在xml标签中直接添加onClick来加入点击事件。

<Button
    android:id="@+id/bt_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/buttonText"
    android:onClick="buClick"/>

然后我们在相对于的java代码中进行逻辑关系的编写,比如我们想在点击按钮后,下面的TextView显示按钮被点击了多少次。

  1. 首先声明两个变量一个tv_text1用以获取TetxView,一个b_number用以记录点击次数
  2. 在onCreate中初始化tv_text1和 b_number
  3. 创建btClick方法,在点击发生时 b_number + 1,并且修改TetxView 的文本
private TextView tv_text1;
private  int b_number;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_button_test);
    tv_text1 = findViewById(R.id.tv_text1);
    b_number = 0;
}


public void btClick(View view){
    b_number++;
    tv_text1.setText("按钮被点击 "+ b_number +"次");
}

点击运行,我们可以看到随着每一次点击,下面TextView都会随之相应变化。

image.png

提示:我们在Android Studio 中写onClick 属性的时候,会给出提示,我们可以看到onClick这个属性被打上了删除线。

image.png

这是因为在onClick这个属性已经过时了,更推荐我们用View.setOnClickListener方式来写。

image.png

那我们关于Button控件就先介绍到这里,在下一篇文章中,我们再来详细的介绍一下Button的点击事件。