안드로이드 컨트롤 사용 시리즈 10:라디오 버튼 사용

안드로이드 라디오 버튼 컨트롤은 일반적으로 말하는 라디오 버튼으로 몇 가지 다른 옵션 중 하나를 선택하는 데 사용된다.다음은 사용법을 여러분께 공유합니다.
이 예는 성별의 선택을 실현하고 남자나 여자를 선택하고 버튼을 누르면 선택한 정보를 표시한다.
주요 사고방식: 한 라디오 그룹 컨트롤에서 두 개의 라디오 버튼 컨트롤을 정의하여 선택한 성별을 나타내는 남자나 여자를 나타낸다.Button 컨트롤을 정의하는 OnClick 이벤트입니다. 이벤트에서 Radio Group 컨트롤에서 Radio Button 컨트롤의 개수를 가져오고 각 Radio Button 컨트롤을 옮겨다니며 컨트롤이 선택된 것을 발견하면 선택한 컨트롤의 내용을 표시합니다.
activity_main.xml 파일:
<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
 <TextView 
     android:id="@+id/textview"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="  :"
     />
 <RadioGroup 
     android:id="@+id/sex"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     >
     <RadioButton 
         android:id="@+id/radiobutton1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text=" "
         />
     <RadioButton 
         android:id="@+id/radiobutton2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text=" "
         />
 </RadioGroup>
 <Button 
     android:id="@+id/button"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="    "
     />
</LinearLayout>

MainActivity.java 파일:
<span style="color:#cc33cc;"> </span>   private RadioGroup group;
    private Button button;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		group=(RadioGroup)findViewById(R.id.sex);
		button=(Button)findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				int len=group.getChildCount();
				String msgString="";
				for(int i=0;i<len;i++){
					RadioButton radioButton=(RadioButton)group.getChildAt(i);
					if(radioButton.isChecked()){
						msgString=radioButton.getText().toString();
						break;
					}
				}
				Toast.makeText(MainActivity.this, msgString, 1).show();
			}
		});
	}

좋은 웹페이지 즐겨찾기