Android edittext onclick事件处理和选择

Leo*_*Leo 1 android onclick selection android-edittext

我有两个编辑文本视图.如果我先点击,我需要选择第一个edittext并设置为第二个"00".喜欢默认的android闹钟.我的问题:

  • 我有api等级10,所以我写不出像:

firstEText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        secondEText.setText("00");
    }
});
Run Code Online (Sandbox Code Playgroud)

如果我使用

firstEText.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        secondEText.setText("00");
    }
});
Run Code Online (Sandbox Code Playgroud)

所以我需要两次点击我的视图.可能的方法:

firstEText.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View view, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            //but with onTouch listener I have problems with 
            //edit text selection:
            ((EditText) view).setSelection(0, ((EditText) view).getText().length());
        }
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

所以我的.setSelection并不总是有效.我的天啊!请帮帮我

Die*_*ino 6

如果我理解正确,您需要执行以下操作:

  • 聚焦时firstEText,选择其中的所有文本firstEText并设置secondEText"00".

我不明白的是为什么你说你不能使用setOnFocusChangeListener,因为它可以从API 1开始使用.

获取焦点在元素上时选择EditText的所有文本的一个方便的属性是android:selectAllOnFocus,它完全符合你的要求.然后,您只需要设置secondEText"00".

UI

<EditText
    android:id="@+id/editText1"
    android:layout_width="180dp"
    android:layout_height="wrap_content"
    android:selectAllOnFocus="true"
    android:background="@android:color/white"
    android:textColor="@android:color/black" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="180dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="@android:color/white"
    android:textColor="@android:color/black" />
Run Code Online (Sandbox Code Playgroud)

活动

firstEText = (EditText) findViewById(R.id.editText1);
secondEText = (EditText) findViewById(R.id.editText2);

firstEText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            secondEText.setText("00");
        }
    }

});
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.