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

android Button 监听的几种方式

2015-09-11 14:20 本站整理 浏览(19)


android Button 监听的几种方式

分类: android2012-10-23
15:20 22587人阅读 评论(4) 收藏 举报
buttonandroidvideomenulayoutclass
android button控件目前主要有如下几种监听方式:
一个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");
			}
		});

多个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;
			}	
		}
	};

多个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;
		}
	}
		
}

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     
}

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