Androidラジオボタンの例

Androidラジオボタンの例

Androidでは、「http://developer.android.com/reference/android/widget/RadioButton.html [android.widget.RadioButton]」クラスを使用してラジオボタンをレンダリングできます。これらのラジオボタンは通常、android.widget.RadioGroupRadioButtonsがグループ内にある場合、グループ内の1つのRadioButtonが選択されると、他のすべてが自動的に選択解除されます。

このチュートリアルでは、XMLを使用して2つのラジオボタンを作成し、ラジオグループにグループ化する方法を示します。 ボタンをクリックすると、選択されているラジオボタンが表示されます。

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. カスタム文字列

res/values/strings.xml」ファイルを開き、ラジオボタンのカスタム文字列を追加します。

ファイル:res / values / strings.xml


    Hello World, MyAndroidAppActivity!
    MyAndroidApp
    Male
    Female
    Display

2. ラジオボタン

res/layout/main.xml」ファイルを開き、「RadioGroup」、「RadioButton」、およびボタンをLinearLayout内に追加します。

ファイル:res / layout / main.xml



    

        

        

    

    

Radio button selected by default.
デフォルトでラジオボタンが選択されるようにするには、android:checked="true"RadioButton要素内に配置します。 この場合、ラジオオプション「男性」がデフォルトで選択されています。

3. コードコード

アクティビティ「onCreate()」メソッド内で、ボタンにクリックリスナーをアタッチします。

ファイル:MyAndroidAppActivity.java

package com.example.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private RadioGroup radioSexGroup;
  private RadioButton radioSexButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
                radioSexButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyAndroidAppActivity.this,
                radioSexButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}

4. Demo

アプリケーションを実行してください。

1. 結果、ラジオオプション「男性」が選択されます。

android radio button demo1

2. 「女性」を選択して「表示」ボタンをクリックすると、選択したラジオボタンの値が表示されます。

android radio button demo2

ソースコードをダウンロード

ダウンロード–Android-RadioButton-Example.zip(15 KB)