package com.czw.click;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private Button btn01,btn02,btn03,btn04,btn05;
private Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn01=(Button) findViewById(R.id.btn01);
btn02=(Button) findViewById(R.id.btn02);
btn03=(Button) findViewById(R.id.btn03);
btn04=(Button) findViewById(R.id.btn04);
btn05=(Button) findViewById(R.id.btn05);
//方法一:匿名内部对象
btn01.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
toast=Toast.makeText(MainActivity.this, "我是按钮一", 0);
toast.show();
}
});
//方法二:监听事件的实现类
btn02.setOnClickListener(new MyListener());
//方法四:使用外部类
btn04.setOnClickListener(new ClickListener(this));
//方法五:让Activity继承监听
btn05.setOnClickListener(this);
}
//方法二:监听事件的实现类<内部类>
class MyListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
toast.setText("我是按钮二");
toast.show();
}
}
//方法三:使用Button属性方法
public void btn03(View view){
toast.setText("我是按钮三");
toast.show();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
toast.setText("我是按钮五");
toast.show();
}
}
外部类代码:
package com.czw.click;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class ClickListener implements OnClickListener{
private Context context;
public ClickListener(Context context){
this.context=context;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "我是按钮四", 0).show();
}
}
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮一" />
<Button
android:id="@+id/btn02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮二" />
<Button
android:onClick="btn03"
android:id="@+id/btn03"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮三" />
<Button
android:id="@+id/btn04"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮四" />
<Button
android:id="@+id/btn05"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮五" />
</LinearLayout>