Header ads

Header ads
» » RadioButton

RadioButton trong Android

Radiobutton thường được đưa ra 2 hoặc nhiều hơn hai phần tử trong đó người dùng chỉ được chọn một phần tử, để làm được như vậy chúng ta cần nhóm chúng vào một nhóm đó chính là GruopRadiobutton để khi người dùng chọn thì chỉ chọn được duy nhất.

RadioButton là một Button gồm có 2 trạng thái checked và unchecked, nếu một button đang ở trạng thái unchecked thì người sử dụng có thể check vào, còn button đang ở trạng thái checked thì người sử dụng không thể unchecked.

Lớp RadioButton là lớp con của lớp CompoundButton.

Các phương của RadioButton 

Lớp RadioButton kế thừa nhiều phương thức của View,TextView hoặc Button

Một vài phương thức thường sử dụng:

Phương thức Ý nghĩa
public boolean isChecked() True nếu CheckBox là checked, ngược lại false
public void setChecked(boolean status) Thay đổi trạng thái của CheckBox

 RadioButton code trong XML

  <RadioButton  android:id="@+id/rdisimpleRadioButton"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:text ="Nữ"/>

Có 2 cách xử lý RadionButton nào được checked như sau:

Cách 1: Dựa vào RadioGroup để biết chính xác Id của RadioButton nào được checked. Dựa vào Id này ta sẽ xử lý đúng nghiệp vụ:

  rdigroupCountry	=	(RadioGroup) findViewById(R.id.rdigroupCountry);  int idChecked	=	rdigroupCountry.getCheckedRadioButtonId();  switch(idChecked){  	case R.id.rdiBrazil:  		 Toast.makeText(getApplication(), "Bạn đã chọn nước Brazil" , Toast.LENGTH_LONG).show();  	    break;  	case R.id.rdiGermany:  		 Toast.makeText(getApplication(), "Bạn đã chọn nước Đức" , Toast.LENGTH_LONG).show();  		 break;  	case R.id.rdiItalia:  		 Toast.makeText(getApplication(), "Bạn đã chọn nước Italia" , Toast.LENGTH_LONG).show();  		break;  	case R.id.rdiVietnam:  		 Toast.makeText(getApplication(), "Bạn đã chọn nước Việt Nam" , Toast.LENGTH_LONG).show();  		break;			  }

Ở ví dụ trên, bạn thấy hàm getCheckedRadioButtonId() : hàm này trả về Id của RadioButton nằm trong RadioGroup 1 được checked. Dựa vào Id này bạn so sánh để biết được trên giao diện người sử dụng đang checked lựa chọn nào.

Cách 2: Kiểm tra trực tiếp từng RadioButton đó có được checked hay không?

  RadioButton rdiBrazil, rdiGermany, rdiVietnam;  rdiBrazil	=	(RadioButton) findViewById(R.id.rdiBrazil);  rdiGermany	=	(RadioButton) findViewById(R.id.rdiGermany);  rdiVietnam	=	(RadioButton) findViewById(R.id.rdiVietnam);  if(rdiBrazil.isChecked())      Toast.makeText(getApplication(), "Bạn đã chọn nước "+rdiBrazil.getText() , Toast.LENGTH_LONG).show();  else if(rdiGermany.isChecked())  	Toast.makeText(getApplication(), "Bạn đã chọn nước "+rdiGermany.getText() , Toast.LENGTH_LONG).show();  else if(rdiVietnam.isChecked())  	Toast.makeText(getApplication(), "Bạn đã chọn nước "+rdiVietnam.getText() , Toast.LENGTH_LONG).show();  

 


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

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

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

   <RadioButton    android:id="@+id/rdisimpleRadioButton"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text ="Nữ" />

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:

  RadioButton chkSimpleRadioButton= (CheckBox) findViewById(R.id.rdisimpleRadioButton);

2. android:checked: checked là thuộc tính của RadioButton dùng để set trạng thái của CheckBox. Giá trị là true hoặc false, nếu giá trị là true thì trạng thái RadioButton checked, ngược lại là false thì trạng thái của RadioButton unchecked. Chúng ta cũng có thể set trạng thái của RadioButton bên Java Code bằng cách dùng phương thức setChecked(boolean status).

  <RadioButton  android:id="@+id/rdisimpleRadioButton"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:checked="true"  android:text ="Nữ" /><!-- set the current state of the radio button-->  

Set trạng thái của RadioButton trong Java Class

  /*Add in Oncreate() funtion after setContentView()*/  // initiate a check box  RadioButton chksimpleRadioButton = (RadioButton) findViewById(R.id.rdisimpleRadioButton);    // set the current state of a check box  chksimpleRadioButton.setChecked(true);

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

  <RadioButton  android:id="@+id/rdisimpleRadioButton"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:checked="true"  android:text ="Nữ"   android:gravity="right|center_vertical"/>  <!-- gravity of the RadioButton-->

4. android:text: thuộc tính text dùng hiển thị nội dung trong một RadioButton. Chúng ta có thể set thuộc tính này trong tập tin xml hoặc java code

  <RadioButton  android:id="@+id/rdisimpleRadioButton"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:checked="true"  android:text ="Hiệp Sĩ IT" /><!--displayed text of the RadioButton-->

Set nội dung trong RadioButton trong Java class:

  /*Add in Oncreate() funtion after setContentView()*/  // initiate check box  RadioButton rdisimpleRadioButton = (RadioButton) findViewById(R.id.rdisimpleRadioButton);    // displayed text of the check box  rdisimpleRadioButton.setText("Hiệp Sĩ IT");

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 nội dung văn bản trong RadioButton  màu đỏ.

  <RadioButton   android:id="@+id/rdisimpleRadioButton"   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:checked="true"   android:text ="Hiệp Sĩ IT"    android:textColor="#f00" /><!--set color  text of the RadioButton-->

Thiết lập thuộc tính textColor trong Java Class

  /*Add in Oncreate() funtion after setContentView()*/  //initiate the checkbox  RadioButton rdisimpleRadioButton  = (RadioButton) findViewById(R.id.chksimpleRadioButton);    //red color for displayed text  rdisimpleRadioButton.setTextColor(Color.RED);

5. android:textSize: Thuộc tính textSize xác định kích thước nội dung văn bản của RadioButton. 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. 

  <RadioButton  android:id="@+id/rdisimpleRadioButton"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:checked="true"  android:text ="Hiệp Sĩ IT"   android:textColor="#f00"  android:textSize="40sp" /><!--set sizetext of the RadioButton-->

Thiết lập thuộc tính textSize trong java class

  /*Add in Oncreate() funtion after setContentView()*/  RadioButton rdisimpleRadioButton  = (RadioButton) findViewById(R.id.rdisimpleRadioButton);  //set 40sp displayed text size  rdisimpleRadioButton.setTextSize(40);

6. android:textStyle: Thuộc tính xác định loại văn bản của RadioButton, 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 RadioButton:

  <RadioButton   android:id="@+id/rdisimpleRadioButton"   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:checked="true"   android:text ="Hiệp Sĩ IT"    android:textSize="40sp"   android:textColor="#f00"   android:textStyle="bold|italic"/><!--set Text style of text in RadioButton-->

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

8. android:padding: Thuộc tính này xác định khoảng cách từ đường viền của RadioButton 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 RadioButton.

  <RadioButton  android:id="@+id/rdisimpleRadioButton"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text ="Hiệp Sĩ IT"   android:textSize="40sp"  android:textColor="#f00"  android:textStyle="bold|italic"  android:checked="false"  android:padding="30dp"/> <!--30dp padding from all side's--> 


Ví dụ: Trong ví dụ này chúng ta sẽ làm app khảo sát đơn giản sau:

Yêu cầu:

  • Tên người không được để trống và phải có ít nhất 3 ký tự
  • Chứng minh nhân dân chỉ được nhập kiểu số và phải có đúng 9 chữ số
  • Bằng cấp mặc định sẽ chọn là Đại học
  • Sở thích phải chọn ít nhất 1 chọn lựa
  • Thông tin bổ sung có thể để trống
  •  Khi bấm gửi thông tin, chương trình sẽ hiển thị toàn bộ thông tin cá nhân cho người sử dụng biết thông qua TextView:

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 đối tượng ToggleButton trong  Linear Layout.

  <LinearLayout xmlns:tools="http://schemas.android.com/tools"      xmlns:android="http://schemas.android.com/apk/res/android"      android:id="@+id/LinearLayout1"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      android:orientation="vertical"      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.radiobutton.MainActivity" >        <TextView          android:id="@+id/txtInfomation"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:background="#cc4"          android:gravity="center"          android:text="@string/information"          android:textAppearance="?android:attr/textAppearanceLarge"          android:textColor="#f00" />        <TableLayout          android:layout_width="fill_parent"          android:layout_height="wrap_content" >            <TableRow              android:id="@+id/tableRow1"              android:layout_width="fill_parent"              android:layout_height="wrap_content" >                <TextView                  android:id="@+id/txtFirstName"                  android:layout_width="wrap_content"                  android:layout_height="wrap_content"                  android:text="@string/firstname" />                <EditText                  android:id="@+id/edtFirstName"                  android:layout_width="200sp"                  android:layout_height="wrap_content" >                    <requestFocus />              </EditText>          </TableRow>            <TableRow              android:id="@+id/tableRow2"              android:layout_width="fill_parent"              android:layout_height="wrap_content" >                <TextView                  android:id="@+id/txtID"                  android:layout_width="wrap_content"                  android:layout_height="wrap_content"                  android:text="@string/id" />                <EditText                  android:id="@+id/edtID"                  android:layout_width="wrap_content"                  android:layout_height="wrap_content"                  android:maxLength="9"                  android:inputType="number" />          </TableRow>      </TableLayout>        <TextView          android:id="@+id/txtDegree"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:background="#fc0"          android:gravity="center"          android:text="@string/degree"          android:textAppearance="?android:attr/textAppearanceLarge"          android:textColor="#f00" />        <RadioGroup          android:id="@+id/rdiGroupDegree"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:orientation="horizontal" >            <RadioButton              android:id="@+id/rdiUniversity"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:checked="true"              android:text="@string/university" />            <RadioButton              android:id="@+id/rdiCollege"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:text="@string/college" />            <RadioButton              android:id="@+id/rdiCollege1"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:text="@string/college1" />      </RadioGroup>        <TextView          android:id="@+id/txtFavorate"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:background="#fc0"          android:textColor="#f00"           android:gravity="center"          android:text="@string/favorate"          android:textAppearance="?android:attr/textAppearanceLarge" />        <LinearLayout          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:orientation="horizontal" >            <CheckBox              android:id="@+id/chkGame"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:text="@string/game" />            <CheckBox              android:id="@+id/chkBook"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:text="@string/book" />            <CheckBox              android:id="@+id/chkNewspaper"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:text="@string/newspaper" />        </LinearLayout>        <TextView          android:id="@+id/txtAddInformaton"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:background="#fc0"          android:textColor="#f00"           android:gravity="center"          android:text="@string/addinformation"          android:textAppearance="?android:attr/textAppearanceLarge" />        <EditText          android:id="@+id/edtAddInformation"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:ems="10"          android:lines="3"          android:inputType="textMultiLine" />        <Button          android:id="@+id/btninsert"          android:layout_width="fill_parent"          android:background="#b00"          android:textColor="#ff0"          android:layout_height="wrap_content"          android:text="@string/btninsert" />        <TextView          android:id="@+id/txtResult"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:inputType="textMultiLine"          android:lines="6"          android:textAppearance="?android:attr/textAppearanceLarge" />    </LinearLayout>

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

Điều khiển android:id android:text
TextView1 txtInformation @string/information
TextView2 txtDegree @string/degree
TextView3 txtFavorate @string/favorate
TextView4 txtAddInformation @string/addinformation
TextView5 txtResult  
EditText1 edtFirstName @string/firstname
EditText2 edtID @string/id
RadioButton1 rdiUniversity @string/university
RadioButton2 rdiCollege @string/college
RadioButton3 rdiCollege @string/college1
CheckBox1 chkGame @string/game
CheckBox2 chkBook @string/book
CheckBox3 chkNewspaper @string/newspaper
Button1 btnInsert @string/btninsert

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

  <resources>      <string name="app_name">Demo RadioButton</string>         <string name="action_settings">Settings</string>  	<string name="information">Thông tin cá nhân</string>  	<string name="firstname">Họ tên</string>  	<string name="id">CMND</string>  	<string name="degree">Bằng cấp</string>  	<string name="university">Đại học</string>  	<string name="college">Cao đẳng</string>  	<string name="college1">Trung cấp</string>  	<string name="favorate">Sở thích</string>  	<string name="game">Chơi game</string>  	<string name="book">Đọc sách</string>  	<string name="newspaper">Đọc báo</string>  	<string name="addinformation">Thông tin khác</string>  	<string name="btninsert">Gởi thông tin</string>  </resources>  

Bước 3: Mở app -> src ->MainActivity.java và thêm code. Khi click vào Button Gởi thông tin, các thông tin được hiển thị qua TextView.

  package hiepsiit.com.radiobutton;    import android.app.Activity;  import android.os.Bundle;  import android.util.Log;  import android.view.Menu;  import android.view.MenuItem;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;  import android.widget.CheckBox;  import android.widget.EditText;  import android.widget.RadioButton;  import android.widget.RadioGroup;  import android.widget.TextView;  import android.widget.Toast;    public class MainActivity extends Activity {  	EditText edtFirstName, edtID, edtInformation;		  	CheckBox chkGame, chkBook, chkNewspaper;  	TextView txtResult;  	Button btnInsert;  	@Override  	protected void onCreate(Bundle savedInstanceState) {  		super.onCreate(savedInstanceState);  		setContentView(R.layout.activity_main);  		edtFirstName	=	(EditText)	findViewById(R.id.edtFirstName);  		edtID			=	(EditText)	findViewById(R.id.edtID);  		edtInformation	=	(EditText)	findViewById(R.id.edtAddInformation);  		chkGame			=	(CheckBox)	findViewById(R.id.chkGame);  		chkBook			=	(CheckBox)	findViewById(R.id.chkBook);  		chkNewspaper	=	(CheckBox)	findViewById(R.id.chkNewspaper);  		btnInsert		=	(Button)	findViewById(R.id.btninsert);  		txtResult		=	(TextView)	findViewById(R.id.txtResult);  		btnInsert.setOnClickListener(new OnClickListener() {  			  			@Override  			public void onClick(View v) {  				// TODO Auto-generated method stub  				showInformation();  			}  		});  		  		  	}  	// Lấy thông tin người sử dụng nhập vào  	private void showInformation(){  		try{  			String message ="";  			//Kiểm tra họ và tên  			String firstname	=	edtFirstName.getText().toString().trim();  			if(firstname.length()<=3){  				edtFirstName.selectAll();  				edtFirstName.requestFocus();  				Toast.makeText(getApplication(), "Họ và tên không nhỏ hơn 3 ký tự", Toast.LENGTH_LONG).show();	  				return;  			}  			message +="Họ và Tên:" +firstname +"\n";  			String strID	=	edtID.getText().toString().trim();  			if(strID.length()!=9){  				edtID.selectAll();  				edtID.requestFocus();  				Toast.makeText(getApplication(), "Số chứng minh nhân dân phải 9 số", Toast.LENGTH_LONG).show();	  				return;  			}  			String degree;  			RadioGroup rdigroupDegree	=	(RadioGroup)	findViewById(R.id.rdiGroupDegree);  			int id	=	rdigroupDegree.getCheckedRadioButtonId();  			  			if(id==-1){  				Toast.makeText(getApplication(), "Xin vui lòng chọn bằng cấp", Toast.LENGTH_LONG).show();	  				return;  			}  			RadioButton	radDegree=	(RadioButton) findViewById(id);	  			degree	=	radDegree.getText()+"";  			message += "Bằng cấp :"+ degree +"\n";  			String favorate="";  			if(chkGame.isChecked())  				favorate+= chkGame.getText()+ " ,";  			if(chkBook.isChecked())  				favorate+= chkBook.getText()+ " ,";  			if(chkNewspaper.isChecked())  				favorate+=chkNewspaper.getText()+ " ";  			  			if(favorate.trim().length()==0){  				Toast.makeText(getApplication(), "Xin vui một sở thích", Toast.LENGTH_LONG).show();	  				return;  			}  			else  				message+="Sở thích: "+ favorate +"\n";  			if(edtInformation.getText().toString().trim().length()!=0)  				message +=	"Thông tin bổ sung:" +edtInformation.getText().toString().trim();  			txtResult.setText(message);  		}  		catch(Exception e){  			Log.d("1", e.getMessage());  		}  	}	  	  }  

Download ví dụ

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


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

Sau khi điền thông tin click vào gởi thông tin kết quả:

 



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