2015年8月27日木曜日

Radioボタンを使ってみる

XMLの記載
RadioGroupで囲むと排他選択になる
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignTop="@+id/radioButton"
        android:layout_alignParentStart="true">
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Xxx"
        android:id="@+id/radioButton"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Yyy"
        android:id="@+id/radioButton2"
        android:layout_below="@+id/radioButton"
        android:layout_alignParentStart="true" />

    </RadioGroup>



java側は以下
1. ハンドラの登録
        // ラジオボタンハンドラ
        RadioButton rbuttonXxx = (RadioButton)findViewById(R.id.radioButton);
        rbuttonXxx.setOnClickListener(new RadioButtonXxxClickListener());

2. ハンドラを記載
    private class RadioButtonXxxClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v){
            // 処理の内容を書く
        }

2015年8月24日月曜日

TextView/EditTextを参照・設定する

EditBox = EditText
Label = TextView
みたいなものでしょうか...

TextViewに文字を表示する
    TextView tv = (TextView) findViewById(R.id.textView);
    tv.setText(string);

EditTextに入力されている文字を取得する
    EditText edv = (EditText) findViewById(R.id.editText);
    String string = edv.getText().toString();

ボタン押下時のイベントハンドラを書く

Androidのイベントハンドラの書き方
今回はボタン押下時のイベント

1. MainActivity.javaのonCreateにハンドラを指定するコードを書く
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new ButtonClickListener()); // 引数にリスナを書く

2. ↑のリスナのクラスを書き、onClickをoverrideする
    private class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v){
            // ここにアクションを書いておく(例:トーストを表示する)
      Toast.makeText(MainActivity.this, "クリックしました", Toast.LENGTH_SHORT).show();
        }
    }