Button的事件方法有两种写法:
第一种是相对与控件较少的情况:
<Button
android:id="@+id/btn_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="click"
android:text="按钮1" />
我们可以在xml文本添加onclick属性然后再mainactivity.java里面写click方法:
//初始化控件
myBtn_one = (Button)findViewById(R.id.btn_one);
//通过实现onclick()方法,实现按钮1的点击事件
public void click(View v){
//写入方法
}
第二种相对那种控件较多的时候采用的方法:
第二种则不需要再mainactivity.xml里面添加onclick属性而是再mainactivity.java里面添加监听事件重写onclick方法然后使用switch循环语句。
//初始化控件
myBtn_two = (Button)findViewById(R.id.btn_two);
myBtn_two = (Button)findViewById(R.id.btn_two); myBtn_one.setOnClickListener(this);
//表示该onclicklistenser的引用
myBtn_two.setOnClickListener(this);
@Override
public void onClick(View v){
switch(v.getId()){
case R.id.btn_one:
myBtn_one.setText("按钮1已被点击");
break;
case R.id.btn_two:
myBtn_two.setText("按钮2已被点击");
break;
}
}