要点:布局文件里Button的onClick属性,给它赋值某个函数名,如“buttonClick”,并在Activity中实现该函数。
下面附上本人的代码。
Activity里有3个Button,布局文件activity_04.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.horrorkwangmail.a20171114.Activity04">
<Button
android:id="@+id/button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Button 1"
android:textAllCaps="false"
app:layout_constraintEnd_toStartOf="@+id/button02"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="buttonClick"/>
<Button
android:id="@+id/button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Button 2"
android:textAllCaps="false"
app:layout_constraintEnd_toStartOf="@+id/button03"
app:layout_constraintStart_toEndOf="@+id/button01"
app:layout_constraintTop_toTopOf="parent"
android:onClick="buttonClick"/>
<Button
android:id="@+id/button03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Button 3"
android:textAllCaps="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/button02"
app:layout_constraintTop_toTopOf="parent"
android:onClick="buttonClick"/>
</android.support.constraint.ConstraintLayout>
文件Activity04.java的代码如下:
package com.horrorkwangmail.a20171114;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import static android.widget.Toast.LENGTH_SHORT;
public class Activity04 extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_04);
getSupportActionBar().hide(); //隐藏标题栏
}
public void buttonClick(View v)
{
switch (v.getId())
{
case R.id.button01:
Toast.makeText(Activity04.this,"You clicked Button 1",LENGTH_SHORT).show();
break;
case R.id.button02:
Toast.makeText(Activity04.this,"You clicked Button 2",LENGTH_SHORT).show();
break;
case R.id.button03:
Toast.makeText(Activity04.this,"You clicked Button 3",LENGTH_SHORT).show();
break;
default:
break;
}
}
}
在手机上测试,效果如下面的gif动图所示。