Android似乎特别灵活,同样一种效果可以有好几种方式来实现。之前我一直使用的是在xml中定义Button,在java文件中获取Button,然后创建监听,并在里面实现响应。后来发现这只是一种比较中规中矩的方法
而已。今天就把它整理出来。
第一步:先创建布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical">
<Button
android:id="@+id/bt_01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按键1"/>
<Button
android:id="@+id/bt_02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按键2"/>
<Button
android:id="@+id/bt_03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click03"
android:text="按键3"/>
</LinearLayout>
第二步:实现部分(为了更加清晰,我在这边将把3种代码分别取出来,最后会有完整的代码部分)
(1)第一种:
Button bt_01 = (Button)findViewById(R.id.bt_01);
bt_01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"this is bt_01",Toast.LENGTH_LONG).show();
}
});
(2)第二种:
Button bt_02 = (Button)findViewById(R.id.bt_02);
bt_02.setOnClickListener(bt_02_Click);
//这是在onCreate(Bundle savedInstanceState)里面定义的
public Button.OnClickListener bt_02_Click = new Button.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"this is bt_02",Toast.LENGTH_LONG).show();
}
};
//响应
(3)第三种:
public void click03(View view){
Toast.makeText(MainActivity.this,"this is bt_03",Toast.LENGTH_LONG).show();
}
ok,接下来将贴上全部的main.java文件上的内容
package com.yueh.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt_01 = (Button)findViewById(R.id.bt_01);
bt_01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"this is bt_01",Toast.LENGTH_LONG).show();
}
});
// 这是第一种常见的使用方法
Button bt_02 = (Button)findViewById(R.id.bt_02);
bt_02.setOnClickListener(bt_02_Click);
// 这是第二种使用方法
}
public Button.OnClickListener bt_02_Click = new Button.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"this is bt_02",Toast.LENGTH_LONG).show();
}
};
// 这是第二种使用方法
public void click03(View view){
Toast.makeText(MainActivity.this,"this is bt_03",Toast.LENGTH_LONG).show();
}
// 这是第三种,在xml布局文件种使用android:onClick来实现的
}