當有多個click事件時的簡易做法

來源:互聯網
上載者:User

標籤:android   style   blog   color   os   io   

讓類實現介面OnClickListener

然後button.setOnClickListener(this);

之後重寫onClick(View v)函數。

通過v.getId()得到是哪個view觸發了click事件。然後分情況處理。如

 1 package com.example.linearlayout; 2  3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.view.Menu; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 10 public class MainActivity extends Activity implements OnClickListener {11     Button tl;12     Button rl;13     Button fl;14     Button al;15 16     @Override17     protected void onCreate(Bundle savedInstanceState) {18         super.onCreate(savedInstanceState);19         setContentView(R.layout.activity_main);20         tl=(Button)findViewById(R.id.button1);21         tl.setOnClickListener(this);22         rl=(Button)findViewById(R.id.button2);23         rl.setOnClickListener(this);24         fl=(Button)findViewById(R.id.button3);25         fl.setOnClickListener(this);26         al=(Button)findViewById(R.id.button4);27         al.setOnClickListener(this);28     }29 30     @Override31     public boolean onCreateOptionsMenu(Menu menu) {32         // Inflate the menu; this adds items to the action bar if it is present.33         getMenuInflater().inflate(R.menu.main, menu);34         return true;35     }36 37     @Override38     public void onClick(View v) {39         // TODO Auto-generated method stub40         if(v.getId()==R.id.button1)41         {42             setContentView(R.layout.tablelayout);43         }44         if(v.getId()==R.id.button2)45         {46             setContentView(R.layout.relativelayout);47         }48         if(v.getId()==R.id.button3)49         {50             setContentView(R.layout.framelayout);51         }52         if(v.getId()==R.id.button4)53         {54             setContentView(R.layout.absolutelayout);55         }56     }57 58 }

上面40到50行中,有4個if語句,用來判斷v是哪一個view。

其實可以通過switch(v.getId())來替換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.