现在的位置: 首页 > 综合 > 正文

android学习(1) – Button单击事件的响应

2013年09月02日 ⁄ 综合 ⁄ 共 2046字 ⁄ 字号 评论关闭

通过Eclipse可以在自己的应用程序中增加一个按钮,同时在main.xml中会自动增加如下的代码:

---

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

编译运行程序时,将会看到一个按钮。单击它时,没有任何的响应和动作。
需要我们手动增加代码为该按钮增加单击事件的响应。

为按钮增加单击事件的响应时有两种方式:
1、通过Button的setOnClickListener方法为该按钮绑定一个单击事件监听器,用于监听用户的单击事件。代码如下:

 public class MyActivity extends Activity {
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         setContentView(R.layout.content_layout_id);

         //手工增加代码开始
         //将按钮绑定一个单操作的事件监听器。用于监听用户的单击操作。
         final Button button = (Button) findViewById(R.id.button_id);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click
                 //增加自己的代码......
                 final TextView text = (TextView) findViewById(R.id.textView1);
                 text.setText("OnClick. " + " ....");	
             }
         });
         //手工增加代码结束
     }
 }

上面的代码很简短,但不利于阅读。也可以使用下面的书写方式:

 public class MyActivity extends Activity {

     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         setContentView(R.layout.content_layout_id);

         //手动增加代码开始
         Button button = (Button) findViewById(R.id.button_id);
         button.setOnClickListener(myOnClickListener);
         //手动增加代码结束
     }

    //手动增加代码开始
    private OnClickListener myOnClickListener = new OnClickListener() {
        public void onClick(View v) {
        //增加自己的代码......
        final TextView text = (TextView) findViewById(R.id.textView1);
        text.setText("OnClick. " + " ....");	           
        }       
    };
    //手动增加代码结束
 }

2、通过修改main.xml中Button的属性,为按钮增加单击事件请求。修改的xml文件如下:

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="OnMySelfClick"
        android:text="Button" />

然后在.java文件中增加xml文件中提到的OnMySelfClick函数:

public class HelloAndroidActivity extends Activity {
    /** Called when the activity is first created. */	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        
    }
    
    /* ************************************
     *   按钮的单击操作处理函数。
     *   下面的函数是一个按钮单击的处理函数。
     *   它需要在layout的xml中将按钮增加一个OnClick的属性,
     *   并指定它的处理函数。如下
     *  
     *   android:onClick="OnMySelfClick"
     *   
     *   这样的话,就不用再增加上面那些复杂的代码了。
     *   
     * */
    public void OnMySelfClick(View v)
    {
		final TextView text = (TextView) findViewById(R.id.textView1);
		text.setText("OnMySelfClick. " + " ....");    
    }
}

第二种方法比较第一种方法简单了许多。

抱歉!评论已关闭.