Android edittext onclick事件处理和选择

时间:2013-07-01 20:51:42

标签: android onclick android-edittext selection

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

  • 我的api等级为10,所以我写不出类似的内容:

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

如果我使用

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

所以我需要两次点击我的视图。可能的解决方案:

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;
    }
});

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

1 个答案:

答案 0 :(得分:6)

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

  • 关注firstEText时,选择firstEText中的所有文字并将secondEText设置为“00”

我不明白为什么你说你不能使用setOnFocusChangeListener,因为it is available since 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" />

<强>活动

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");
        }
    }

});

希望它有所帮助。

相关问题