1. 程式人生 > >android Button 監聽的幾種方式

android Button 監聽的幾種方式

android button控制元件目前主要有如下幾種監聽方式:

  1. 一個button控制元件對應一個監聽:
            Button buttontest;
            buttontest = (Button) findViewById(R.id.button1);
            buttontest.setOnClickListener(new View.OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				Log.i("TEST", "button onClick");
    			}
    		});
  2. 多個button對應一個監聽1:
    start = (Button) findViewById(R.id.button1);
    stop = (Button) findViewById(R.id.button2);
    start.setOnClickListener(mylistener );
    stop.setOnClickListener(mylistener );
    View.OnClickListener mylistener = new View.OnClickListener() {
    		
    		@Override
    		public void onClick(View v) {
    			switch (v.getId()) {
    			case R.id.button1:
    				Log.d(TAG, "Start to recorder video\n");
    				start_recorde();
    				break;
    			case R.id.button2:
    				Log.d(TAG, "Stop to recorder video\n");
    				stop_recorde();
    				break;
    			default:
    				break;
    			}	
    		}
    	};
  3. 多個button對應一個監聽2:
    public class MainActivity extends Activity implements View.OnClickListener{
    	//介面元素
    	private Button start;
    	private Button stop;
    	
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            start = (Button) findViewById(R.id.button1);
            stop = (Button) findViewById(R.id.button2);
            start.setOnClickListener(this);
            stop.setOnClickListener(this);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    
    	@Override
    	public void onClick(View v) {
    		switch (v.getId()) {
    		case R.id.button1:
    			Log.d(TAG, "Start to recorder video\n");
    			break;
    		case R.id.button2:
    			Log.d(TAG, "Stop to recorder video\n");
    			break;
    		default:
    			break;
    		}
    	}
    		
    }
  4. xml中繫結監聽:
    <Button 
    android:id="@+id/button1" 
    android:layout_height="wrap_content"          
    android:layout_width="wrap_content" 
    android:onClick="mybuttonlistener">
    </Button>
    對應java程式碼如下:
    Button btn = (Button) findViewById(R.id.button1);
    public void mybuttonlistener(View target){
        //do something5     
    }

    從個人角度來講,不推薦使用第四種實現方式。