android 初學之Listener

來源:互聯網
上載者:User

標籤:android   blog   http   io   ar   java   sp   strong   div   


1)第一種,也是最長見的添加方法(一下都以Button為例)

 

1 Button btn = (Button) findViewById(R.id.myButton);
2 btn .setOnClickListener(new View.OnClickListener() {
3 public void onClick(View v) {
4 //do something
5 }
6 });



2)第二種,下面這個方法較前一種稍微簡單了一些,允許多個Buttons共用一個Listener。通過Switch控制對不同Button Click事件的回應程式法:

 1 Button btn = (Button) findViewById(R.id.mybutton);
2 Button btn2 = (Button) findViewById(R.id.mybutton2);
3 btn.setOnClickListener(handler);
4 btn2.setOnClickListener(handler);
5 View.OnClickListener handler = View.OnClickListener() {
6 public void onClick(View v) {
7 switch (v.getId()) {
8 case R.id.mybutton:
9 //do something
10 break;
11 case R.id.mybutton2:
12 //do something
13 break;
14 }
15 }




3)第三種,直接將Clicklistener捆綁XML layout中的Views元素,在程式中定義的Listener方法需要帶有一個View類型的參數:

 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical" android:layout_width="fill_parent"
4 android:layout_height="fill_parent">
5 <TextView android:layout_width="fill_parent"
6 android:layout_height="wrap_content" android:id="@+id/text"
7 android:text="@string/hello" />
8 <Button android:id="@+id/mybutton" android:layout_height="wrap_content"
9 android:layout_width="wrap_content" android:onClick="mybuttonlistener"></Button>
10 </LinearLayout>

 

java代碼:

1 Button btn = (Button) findViewById(R.id.mybutton);
2
3 public void mybuttonlistener(View target){
4 //do something
5 }

android 初學之Listener

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.