監聽事件的三種寫法

//監聽事件的三種寫法:匿名內部類,獨立類監聽按鈕點擊事件 , 實現接口

//strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">EventMonitor</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="button_name">登陸</string>
</resources>

//activity_main.xml

<RelativeLayout 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="com.vincentlin.eventmonitor.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/button_name" />
    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:src="@drawable/ic_launcher" />
</RelativeLayout>

//MainActivity.java

package com.vincentlin.eventmonitor;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
public class MainActivity extends Activity implements OnClickListener{
 /**
  * Button---可以設置文本內容一個按鈕
  * ImageButton(src屬性,background屬性-不可以設置文本內容,但可以通過用background以及src添加一個image,
     * 當前圖片上可以做一個有文本內容的圖片)
  */
 private Button loginButton;
 private ImageButton imageButton;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  /*
   * 1)初始化當前所需控件,如何初始化一個控件?
   * findViewById--返回的是一個View對象
   * findViewById如何查找對應的view的id
   * 2)設置Button的監聽器,通過監聽器實現我們點擊Button要操作的事情
   */
  loginButton = (Button) findViewById(R.id.button1);
  imageButton = (ImageButton) findViewById(R.id.imageButton1);
  //監聽事件通過第一種方式實現(匿名內部類)
  /*loginButton.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    //在當前onClick方法中監聽點擊Button的動作
    System.out.println("匿名內部類事件的監聽事件");
   }
  });*/
  //監聽事件通過第二種方式實現(獨立類實現)
  /*loginButton.setOnClickListener(listener);*/
  
  //監聽事件通過第三種方式實現(接口實現)
  //先實現一個接口 implements OnClickListener
  imageButton.setOnClickListener(this);
  
 }
 @Override
 public void onClick(View v) {
  Log.i("tag", "接口事件監聽事件");
  
 }
 
 /*OnClickListener listener = new OnClickListener() {
  
  @Override
  public void onClick(View v) {
   //System.out.println("獨立類實現的監聽事件");
   Log.i("tag", "獨立類實現的監聽事件");
  }
 };*/
 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章