1. 匿名內部類作為事件監聽器 2. 內部類作為事件監聽器 3. Activity本身作為事件監聽器 4. 外部類作為事件監聽器 5. 將事件處理方法直接綁定到標簽 ...
匿名內部類作為事件監聽器
public class MainActivity extends Activity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("匿名內部類作為事件監聽器"); } }); } }
內部類作為事件監聽器
public class MainActivity extends Activity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new ButtonOnClickListener()); } class ButtonOnClickListener implements OnClickListener{ @Override public void onClick(View v) { System.out.println("內部類作為事件監聽器"); } } }
Activity本身作為事件監聽器
public class MainActivity extends Activity implements OnClickListener{ private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button1); button.setOnClickListener(this); } @Override public void onClick(View v) { System.out.println("Activity本身作為事件監聽器"); } }
外部類作為事件監聽器
public class MainActivity extends Activity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new ButtonOnClickListener()); } } class ButtonOnClickListener implements OnClickListener { @Override public void onClick(View v) { System.out.println("外部類作為事件監聽器"); } }
將事件處理方法直接綁定到標簽
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="點擊事件" android:onClick="onClick" />
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClick(View v){ System.out.println("將事件處理方法直接綁定到標簽"); } }