轉載請注明出處:http://blog.csdn.net/mr_leixiansheng/article/details/58597469
1、匿名內部類監聽
2、外部類監聽
3、接口實現監聽
代碼如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/button" android:text="常規按鈕" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageButton android:id="@+id/image_button" android:src="@mipmap/ic_launcher" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>package com.example.leixiansheng.buttonimagebutton;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.Toast;/** * Created by Leixiansheng on 2017/2/28. *//** * 1、明白Button和ImageButton的用法和區別 * 2、3種監聽方式(內部監聽、外部監聽、接口監聽) */public class MainActivity extends AppCompatActivity { PRivate Button button; private ImageButton imageButton; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); button = (Button) findViewById(R.id.button); imageButton = (ImageButton) findViewById(R.id.image_button); //1、內部類監聽(直接new View.OnClickListener使用)// button.setOnClickListener(new View.OnClickListener() {// @Override// public void onClick(View view) {// Toast.makeText(MainActivity.this, "點擊了按鈕",Toast.LENGTH_SHORT).show();// }// });// imageButton.setOnClickListener(new View.OnClickListener() {// @Override// public void onClick(View view) {// Toast.makeText(MainActivity.this, "點擊了按鈕",Toast.LENGTH_SHORT).show();// }// }); //2、外部類監聽(1、外面先寫一個類并繼承監聽 2、調用這個外部類實現監聽) // 作用:解決代碼復用,比如每個按鍵都需要實現點擊后變透明,只需一個外部類即可 MyListener listener = new MyListener(); button.setOnClickListener(listener); imageButton.setOnClickListener(new MyListener(){ @Override public void onClick(View view) { super.onClick(view); Toast.makeText(view.getContext(), "點擊了特殊按鈕",Toast.LENGTH_SHORT).show(); } }); //3、接口監聽(實現View.OnClickListener)// button.setOnClickListener(this);// imageButton.setOnClickListener(this); }// 接口實現監聽// @Override// public void onClick(View view) {// switch (view.getId()) {// case R.id.button://// break;// case R.id.image_button://// break;//// }// }}//外部類實現監聽class MyListener implements View.OnClickListener { @Override public void onClick(View view) { view.setAlpha(0.5f); }}
新聞熱點
疑難解答