当前位置:首页 » Android开发技术

android Button 监听的几种方式

2015-01-27 09:35 本站整理 浏览(14)
android button控件目前主要有如下几种监听方式:
一个button控件对应一个监听:
[java] view plaincopy      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");  
    }  
});  

多个button对应一个监听1:[java] view plaincopystart = (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;  
            }     
        }  
    };  

多个button对应一个监听2:[java] view plaincopypublic 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;  
        }  
    }  
          
}  

xml中绑定监听:[html] view plaincopy<Button   
android:id="@+id/button1"   
android:layout_height="wrap_content"            
android:layout_width="wrap_content"   
android:onClick="mybuttonlistener">  
</Button>  
对应java代码如下:[java] view plaincopyButton btn = (Button) findViewById(R.id.button1);  
public void mybuttonlistener(View target){  
    //do something5       
}  

从个人角度来讲,不推荐使用第四种实现方式。