goo blog サービス終了のお知らせ 

marunomaruno-memo

marunomaruno-memo

Android ダイアログ (3) テキスト入力

2011年08月06日 | Android
ダイアログ (3) テキスト入力
================================================================================

■ テキスト入力

ダイアログを使って、テキストを入力することもできる。
これも、AlertDialogを使う。実際には、テキスト入力だけではなく、カスタムダイアロ
グとして、いろいろと使える。


□ Dialog04Activity.java
---
package jp.marunomaruno.android.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class Dialog04Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final TextView textView = (TextView) findViewById(R.id.name);
        final EditText editText = new EditText(this);                    // (1)

        new AlertDialog.Builder(this)
                .setTitle(R.string.alertDialogTitle)
                .setMessage(R.string.alertDialogMessage)
                .setPositiveButton(R.string.alertDialogPositiveButton,
                        new OKButtonClickHandler(textView, editText))
                .setView(editText)                                       // (2)
                .show();
    }

    /**
     * OKボタンをクリックしたときのハンドラー
     */
    private class OKButtonClickHandler implements OnClickListener {
        TextView textView;
        EditText editText;

        public OKButtonClickHandler(TextView textView, EditText editText) {
            this.textView = textView;
            this.editText = editText;
        }

        @Override
        public void onClick(DialogInterface dialog,
                int which) {
            textView.setText(String
                    .format(getString(R.string.alertDialogResultFormat), // (3)
                            editText.getText()));
        }
    }
}
---

(1)      android.widget.EditText

テキストを入力するビューのクラス。

主なメソッド
CharSequence getText()

void  setText(int resid)
void  setText(char[] text, int start, int len)
void  setText(int resid, TextView.BufferType type)
void  setText(CharSequence text)
void  setText(CharSequence text, TextView.BufferType type)


今回は使っていないが、テキストの範囲選択関係のメソッド。これらは、
android.text.Selection クラスのメソッドを使いやすくしたものとして定義されている。

void  extendSelection(int index)         カーソルの現在位置からindexまで選択
void  selectAll()                        すべて選択
void  setSelection(int start, int stop)  startからstopまで選択

カーソルの移動メソッド
void  setSelection(int index)            indexに移動


android.widget.TextView.BufferType
enumとして定義されている。

TextView.BufferType  EDITABLE
TextView.BufferType  NORMAL       
TextView.BufferType  SPANNABLE       


(2) setView(editText)

編集ビューをダイアログに設定する。


(3) OKボタンをクリックしたら、編集ビューの値(テキスト)を取得して、それをもとにテ
キスト・ビューにその値を設定する。

実際には、String.format()メソッドのフォーマットは、リソースで定義している "%s さ
ん、こんにちは!" という形式。%s のところに、editText.getText() で値を持ってきて
いる。


□ res/layout/main.xml
---

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    
<TextView  
    android:id="@+id/name"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
</LinearLayout>
---

□ res/values/strings.xml
---

<resources>
    <string name="alertDialogTitle">名前入力</string>
    <string name="alertDialogMessage">名前を入力してください</string>
    <string name="alertDialogPositiveButton">OK</string>
    <string name="alertDialogResultFormat">%s さん、こんにちは!</string>
    <string name="app_name">Dialog04</string>
</resources>
---


■ 最初からソフトキーボードを表示

Dialog04のサンプルでは、入力エリアをクリックしないと、ソフトキーボードは表示され
ませんでした。
最初からソフトキーボードが表示されいた方がよいこともあります。
このサンプルでは、最初からソフトキーボードを表示するようにします。


□ Dialog041Activity.java
---
package jp.marunomaruno.android.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TextView;

public class Dialog041Activity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final TextView textView = (TextView) findViewById(R.id.name);
        final EditText editText = new EditText(this);

        final AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle(R.string.alertDialogTitle)
                .setMessage(R.string.alertDialogMessage)
                .setPositiveButton(R.string.alertDialogPositiveButton,
                        new OKButtonClickHandler(textView, editText))
                .setView(editText)
                .create();
        
        editText.setOnFocusChangeListener(new ForcusChangeHandler(alertDialog));// (1)

        alertDialog.show();
    }

    /**
     * フォーカスが変化したときのハンドラー
     */
    private class ForcusChangeHandler implements OnFocusChangeListener {        // (2)
        AlertDialog dialog;
        
        public ForcusChangeHandler(AlertDialog dialog) {
            this.dialog = dialog;
        }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {                   // (3)
            if (hasFocus) {
                dialog.getWindow().setSoftInputMode(                            // (4)
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        }
    }
    
    /**
     * OKボタンをクリックしたときのハンドラー
     */
    private class OKButtonClickHandler implements OnClickListener {
        TextView textView;
        EditText editText;

        public OKButtonClickHandler(TextView textView, EditText editText) {
            this.textView = textView;
            this.editText = editText;
        }

        @Override
        public void onClick(DialogInterface dialog,
                int which) {
            textView.setText(String
                    .format(getString(R.string.alertDialogResultFormat),
                            editText.getText()));
        }
    }
}
---

(1) setOnFocusChangeListener

View クラスのメソッド。

public void setOnFocusChangeListener (View.OnFocusChangeListener l)


(2) android.view.View.OnFocusChangeListener
(3) void onFocusChange(View v, boolean hasFocus)

ビューのフォーカスが変わったことを検知するリスナーのインターフェースと、そのハン
ドラーのメソッド。


(4) dialog.getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

ダイアログのウィンドウに対して、softInputModeを設定する。設定する値は、
WindowManager.LayoutParamsクラスのSOFT_INPUT_STATE_xxx定数で指定する。
今回は、ダイアログがフォーカスを受けたときには常にソフトキーボ-ドを表示したいの
で、SOFT_INPUT_STATE_ALWAYS_VISIBLE を指定する。

これが、SOFT_INPUT_STATE_VISIBLE だと、ダイアログがたとえ表示されていたとしても、
自分でフォーカスを当てない限り、ソフトキーボードが表示されない。


WindowManager.LayoutParams

ソフトウェア入力の状態を示す定数には以下のものがある。

int SOFT_INPUT_STATE_ALWAYS_HIDDEN   
        ウィンドウがフォーカスを受けたときに常に soft input area を隠す
int SOFT_INPUT_STATE_ALWAYS_VISIBLE  
        ウィンドウがフォーカスを受けたときに常に soft input area を表示する
int SOFT_INPUT_STATE_HIDDEN          
        通常、適切なとき(ユーザがウィンドウを前面に持ってきたとき)に soft 
        input area を隠す
int SOFT_INPUT_STATE_UNCHANGED       
        soft input area の状態を変更しない
int SOFT_INPUT_STATE_UNSPECIFIED     
        状態は指定されていない
int SOFT_INPUT_STATE_VISIBLE         
        通常、適切なとき(ユーザがウィンドウを前面に持ってきたとき)に soft 
        input area を表示する 

上記以外にも、いろいろな種類の定数が定義されている。また、これらは次のフィールド
の値として管理されている。

public int softInputMode

関連するものとしては、
    SOFT_INPUT_ADJUST_UNSPECIFIED
    SOFT_INPUT_ADJUST_RESIZE
    SOFT_INPUT_ADJUST_PAN
などがあり、値を取り出すための
    SOFT_INPUT_IS_FORWARD_NAVIGATION
    SOFT_INPUT_MASK_ADJUST
    SOFT_INPUT_MASK_STATE
    SOFT_INPUT_MODE_CHANGED
などのマスクが用意されている。



最新の画像もっと見る

コメントを投稿