Android-常用标签-Button的事件方法

人走茶凉 提交于 2020-02-27 14:27:52

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!