カーソルを指定の位置に移動

広告

テキストボックス内でカーソルを指定した位置へ移動する方法を確認します。「EditText」クラスで用意されている「setSelection」メソッドを使います。

Move the cursor to offset index.

Parameters:
  index  カーソルを移動させる位置

引数にテキストボックス内でカーソルを移動させる位置をint型の値で指定します。最初の文字の前の位置が「0」となります。

具体的には次のように記述します。

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

public class Test extends Activity {
    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        EditText edit = new EditText(this);
        edit.setHeight(50);
        setContentView(edit);

        edit.setSelection(4);
    }
}

サンプルプログラム

それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。

Test06_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.TextView.BufferType;

public class Test06_01 extends Activity {
    private final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;

    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(linearLayout);

        TextView tv = new TextView(this);
        tv.setText("What's your name?");
        linearLayout.addView(tv, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        final EditText edit = new EditText(this);
        edit.setWidth(200);
        edit.setText("Takahashi", BufferType.NORMAL);
        linearLayout.addView(edit, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        Button button1 = new Button(this);
        button1.setText("move 4 index position");
        button1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                edit.setSelection(4);
            }
        });
        linearLayout.addView(button1, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        Button button2 = new Button(this);
        button2.setText("move last position");
        button2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                CharSequence str = edit.getText();
                edit.setSelection(str.length());
            }
        });
        linearLayout.addView(button2, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}

ビルド後にエミュレーター上で実行します。

カーソルを指定の位置に移動

ボタンが2つ設置されています。上のボタンをクリックすると4番目の位置にカーソルが移動します。

カーソルを指定の位置に移動

下のボタンをクリックすると入力されている文字列の最後の位置にカーソルが移動します。

カーソルを指定の位置に移動

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。