Header ads

Header ads
» » Button

Button trong Android

Button là một thành phần cho phép chúng ta click vào để thao tác thực hiện xử lý một điều gì đó. Để xử lý được thì cần thêm code bên Java.Có 3 loại 3 Button khác nhau:CompoundButton, ToggleButton, RadioButton.

Butoon kế thừa từ TextView. Do đó, một Button kế thừa tất cả thuộc tính của TextView

Control này kế thừa từ TextView và cho phép chỉnh sửa dữ liệu (dĩ nhiên chúng ta có thể cấm chỉnh sửa dữ liệu bằng coding hay trong xml). Để sử dụng EditText rất đơn giản, chúng ta chỉ việc kéo thả control này vào giao diện và tiến 

Chúng ta có thể tạo một Button trong tập tin XML hoặc khởi tạo Button trong code Java

Code Button trong XML

   <Button    android:id="@+id/btnSimple"    android:layout_width="fill_parent"    android:layout_height="wrap_content"                android:layout_marginTop="38dp"    android:text="Hiep Si IT" />  

Code Button trong JAVA

  Button btnSimple= (Button) findViewById(R.id.btnSimple);  btnSimple.setText("Hiệp Sĩ IT"); //set text for Button

 


Thuộc tính thường dùng của Button

Bây giờ chúng xem một số thuộc tính hay sử dụng trong Button trong tập tin XML

1. android:id: Là thuộc tính duy nhất của Button. Xem ví dụ sau:

   <Button    android:id="@+id/btnSimple"    android:layout_width="fill_parent"    android:layout_height="wrap_content"                android:layout_marginTop="38dp"    android:text="Hiep Si IT" />  

Dựa vào Id ta sẽ lấy được control theo đúng Id này, xem code bên dưới để biết cách lấy control theo Id:

  Button btnSimple= (Button) findViewById(R.id.btnSimple);

2. android:gravity: Thuộc tính này thường sử dụng để canh nội dung trên EditText: left, right, center, top, bottom, center_vertical, center_horizontal.

  <Button  android:id="@+id/btnSimple"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_marginTop="28dp"  android:gravity="right|center_vertical"  android:text="Hiep Si IT" />

3. android:text: Thuộc tính này dùng xuất chuỗi văn bản lên Button, Chúng ta có thể khai báo trong XML hoặc code Java.

  <Button  android:id="@+id/btnSimple"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_marginTop="28dp"  android:gravity="right|center_vertical"  android:text="Hoc Android @Hiep Si IT" />  

Set chuỗi văn bản trong Java Class:

  Button btnSimple= (Button) findViewById(R.id.btnSimple);  btnSimple.setText("Hoc Android @ Hiệp Sĩ IT"); //set text for Button

4. android:textColor: Thuộc tính này dùng xác định màu chữ, dạng màu chữ: “#argb”, "#rgb”, “#rrggbb”, hoặc “#aarrggbb”. Vi dụ sau set chữ trong Button màu đỏ.

  <Button  android:id="@+id/btnSimple"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_marginTop="28dp"  android:gravity="center"  android:textColor="#f00"  android:text="Hiep Si IT" />

Set thuộc tính textColor cho Button trong Java class:

  Button btnSimple=(Button)findViewById(R.id.btnSimple);  btnSimple.setTextColor(Color.RED);//set the red text color

5. android:textSize: Thuộc tính textSize xác định kích thước văn bản của Button. Chúng ta có thể đặt kích thước văn bản theo: sp(scale independent pixel) hoặc dp(density pixel). Trong ví dụ này chúng ta xác định kich thước cho văn bản là 40sp. 

  <Button  android:id="@+id/btnSimple"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_marginTop="28dp"  android:gravity="center"  android:textColor="#f00"  android:textSize="40sp"  android:text="Hiep Si IT" />

6. android:textStyle: Thuộc tính xác định loại văn bản của Button, thông thường có các loại văn bản:bold, italic và normal. Nếu chúng ta muốn sử nhiều hơn một loại văn bản thì phải thêm phép toán hoặc "|" vào giữa các loại văn bản. Trong ví dụ sau chúng ta set bold và italic cho chuỗi văn bản của Button:

  <Button  android:id="@+id/btnSimple"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_marginTop="28dp"  android:gravity="center"  android:textColor="#f00"  android:textSize="40sp"  android:text="Hiep Si IT"   android:textStyle="bold|italic"/><!--set bold and italic text style-->

7. android:background: Thuộc tính này xác định màu nền cho Button

8. android:padding: Thuộc tính này xác định khoảng cách từ đường viền của Button với nội dung nó chứa: left, right, top or bottom. Cũng ví dụ trên bây giờ chúng ta xác định padding=10sp từ mọi phía của Button.

  <Button  android:id="@+id/btnSimple"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_marginTop="28dp"  android:textSize="40sp"  android:text="Hiep Si IT"   android:padding="15dp"  android:textStyle="bold|italic"  android:background="#FFCC" />

Set thuộc tính Background cho Button trong Java class:

  Button simpleButton=(Button)findViewById(R.id.btnSimple);  simpleButton.setBackgroundColor(Color.BLACK);//set the black color of button background

9. android:drawableBottom: drawableBottom hiển thị icon sau chuỗi văn bản.

  <Button  android:id="@+id/btnSimple"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_marginTop="28dp"  android:textSize="40sp"  android:text="Hiep Si IT"   android:padding="15dp"  android:textStyle="bold|italic"  android:background="#FFCC"   android:drawableBottom="@drawable/ic_launcher"/><!--image drawable on button-->

10. android:drawableTop, android:drawableRight và android:drawableLeft: Hiển thị Icon bên trái,bên

 phải hoặc phía trên của chuỗi văn bản. Ví dụ sau hiển thị Icon bên phải chuỗi văn bản:

  <Button  android:id="@+id/btnSimple"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"  android:layout_alignParentTop="true"  android:layout_marginTop="28dp"  android:textSize="40sp"  android:text="Hiep Si IT"   android:padding="15dp"  android:textStyle="bold|italic"  android:background="#FFCC"   android:drawableRight="@drawable/ic_launcher"/><!--image drawable on Right side of Text on button-->  


Ví dụ: Trong ví dụ này chúng ta sẽ làm app tổng 2 số nguyên, kết quả  hiển thị các giá trị này lên TextView thông qua một button được lập trình xử lý sự kiện trong Java Clas.  Tiến hành tạo project, vào thư mục  res /layout -> activity_main.xml  thiết kế giao diện sau:

Bước 1: Tạo một project tên là TextView: File->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code, chúng ta sẽ tạo các TextView, EditText Button trong  Relative Layout.

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:paddingBottom="@dimen/activity_vertical_margin"      android:paddingLeft="@dimen/activity_horizontal_margin"      android:paddingRight="@dimen/activity_horizontal_margin"      android:paddingTop="@dimen/activity_vertical_margin"      tools:context="hiepsiit.com.button.MainActivity" ><!--set the gravity of button--><!--image drawable on Right side of Text on button-->        <TextView          android:id="@+id/txtLabel"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_alignParentTop="true"          android:layout_centerHorizontal="true"          android:text="@string/txtlabel"          android:textSize="30sp"          android:textColor="#ff00"          android:textStyle="bold|italic"          android:textAppearance="?android:attr/textAppearanceLarge" />            <TextView          android:id="@+id/txtNumA"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_alignParentTop="true"          android:layout_marginTop="56dp"          android:text="@string/txtnuma" />        <EditText          android:id="@+id/edtNumA"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_alignBaseline="@+id/txtNumA"          android:layout_alignBottom="@+id/txtNumA"          android:layout_alignLeft="@+id/txtLable"          android:ems="10"          android:inputType="number" >            <requestFocus />      </EditText>        <TextView          android:id="@+id/txtNumB"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_alignLeft="@+id/txtNumA"          android:layout_below="@+id/edtNumA"          android:layout_marginTop="35dp"          android:text="@string/txtnumb" />        <EditText          android:id="@+id/edtNumB"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_alignBaseline="@+id/txtNumB"          android:layout_alignBottom="@+id/txtNumB"          android:layout_alignLeft="@+id/edtNumA"          android:ems="10"          android:inputType="number" />        <TextView          android:id="@+id/txtResult"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:layout_alignLeft="@+id/txtNumB"          android:layout_below="@+id/edtNumB"          android:layout_marginTop="25dp" />        <Button          android:id="@+id/btnClear"          android:layout_width="130sp"          android:layout_height="wrap_content"          android:layout_alignBaseline="@+id/btnSum"          android:layout_alignBottom="@+id/btnSum"          android:layout_marginLeft="30dp"          android:layout_toRightOf="@+id/btnSum"          android:text="@string/btnclear" />        <Button          android:id="@+id/btnSum"          android:layout_width="130sp"          android:layout_height="wrap_content"          android:layout_alignTop="@+id/txtResult"          android:layout_marginTop="28dp"          android:layout_below="@+id/txtResult"          android:text="@string/btnsum" />        </RelativeLayout>

Chuyển quan XML đổi tên các điều khiển: 

Điều khiển android:id android:text
TextView2 txtLabel @string/txtlabel
TextView1 txtNumA @string/txtnuma
TextView2 txtNumB @string/txtnumb
TextView3 txtResult  
EditText1 edtNumA  
EditText2 edtNumB  
Button1 btnSum @string/btnSum
Button2 btnClear @string/btnClear

Vào thư mục res/values bổ sung string.xml (Chúng ta không khai báo trực tiếp nhãn vào các điều khiển, mà thông qua string.xml)

  <string name="txtlabel">Tổng hai số</string>  <string name="txtnuma">Nhập số a:</string>  <string name="txtnumb">Nhập số b:</string>  <string name="btnsum">Tổng</string>  <string name="btnclear">Xóa trắng</string>

Bước 3: Mở app -> src ->MainActivity.java và thêm code. Khi click vào Button gọi phương thức sum(a,b), trong phương thức này chúng ta truyền 2 tham số lấy từ 2 EditText, sau đó hiển thị lên TextView

  package hiepsiit.com.button;    import android.app.Activity;  import android.graphics.Color;  import android.os.Bundle;  import android.view.Menu;  import android.view.MenuItem;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;  import android.widget.EditText;  import android.widget.TextView;  import android.widget.Toast;    public class MainActivity extends Activity {  	Button btnSum, btnClear;  	EditText edtNumA, edtNumB;  	TextView txtResult;  	@Override  	protected void onCreate(Bundle savedInstanceState) {  		super.onCreate(savedInstanceState);  		setContentView(R.layout.activity_main);  		edtNumA	=	(EditText)findViewById(R.id.edtNumA);  		edtNumB	=	(EditText)findViewById(R.id.edtNumB);  		txtResult=	(TextView)findViewById(R.id.txtResult);  		btnSum	=	(Button)findViewById(R.id.btnSum);  		btnClear=	(Button)findViewById(R.id.btnClear);	  		btnSum.setOnClickListener(new OnClickListener() {  			  			@Override  			public void onClick(View v) {  				// TODO Auto-generated method stub  				float a, b, c;  				a	=	Float.parseFloat(edtNumA.getText().toString());  				b	=	Float.parseFloat(edtNumB.getText().toString());  				c	=	a	+	b;  				txtResult.setText("Tổng 2 số là: "+c);  				txtResult.setBackgroundColor(Color.GREEN);  				  			}  		});  		  		btnClear.setOnClickListener(new OnClickListener() {  			  			@Override  			public void onClick(View v) {  				// TODO Auto-generated method stub  				edtNumA.setText("");  				edtNumB.setText("");  			}  		});  	}  	  	private float Sum(float a, float b){  	 try{  		 return a+b;  	 }  	 catch (Exception ex){  		Toast.makeText(getApplication(), "Xin vui lòng nhập số", Toast.LENGTH_LONG).show();  	 }  	 return 0;  	}  	  }  

 


Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11  and target sdk 21.


Kết quả khi chạy ứng dụng:

Sau đó nhập 2 số a và b, Click vào Button "Tổng":



Cập nhật công nghệ từ Youtube tại link: https://www.youtube.com/channel/UCOxeYcvZPGf-mGLYSl_1LuA/videos
Để tham gia khóa học công nghệ truy cập link: http://thuvien.hocviendaotao.com
Mọi hỗ trợ về công nghệ email: dinhanhtuan68@gmail.com

About Học viện đào tạo trực tuyến

Xinh chào bạn. Tôi là Đinh Anh Tuấn - Thạc sĩ CNTT. Email: dinhanhtuan68@gmail.com .
- Nhận đào tạo trực tuyến lập trình dành cho nhà quản lý, kế toán bằng Foxpro, Access 2010, Excel, Macro Excel, Macro Word, chứng chỉ MOS cao cấp, IC3, tiếng anh, phần mềm, phần cứng .
- Nhận thiết kế phần mềm quản lý, Web, Web ứng dụng, quản lý, bán hàng,... Nhận Thiết kế bài giảng điện tử, số hóa tài liệu...
HỌC VIỆN ĐÀO TẠO TRỰC TUYẾN:TẬN TÂM-CHẤT LƯỢNG.
«
Next
Bài đăng Mới hơn
»
Previous
Bài đăng Cũ hơn