Android下按钮的使用方法


Android下按钮的使用方法:

  1. package com.hangsheng.button;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.widget.Button;  
  7.   
  8. public class Ex07_WidgetButtonActivity extends Activity {  
  9.     /** Called when the activity is first created. */  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);   //关联布局模板文件main.xml   
  14.         find_and_modify_button();        //调用成员函数find_and_modity_button   
  15.     }  
  16.    private void find_and_modify_button(){  
  17.        Button button =(Button)findViewById(R.id.button);        //通过资源内ID为button的资源来实例化button对象   
  18.        button.setOnClickListener(button_listener);              //设置对象button的监听器   
  19.          
  20.    };  
  21.    private Button.OnClickListener button_listener =new Button.OnClickListener(){  //成员按钮监听对象   
  22.     @Override  
  23.     public void onClick(View v) {                                             //按钮事件   
  24.         // TODO Auto-generated method stub   
  25.         setTitle("button被点击了一下");  
  26.     }  
  27.    };  
  28. }  

布局模板文件main.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/hello" />  
  11.   
  12.     <Button  
  13.         android:id="@+id/button"  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="这是Button" />  
  17.   
  18. </LinearLayout>  

相关内容