Android edittext onclick event handling and selection

流过昼夜 提交于 2019-12-11 04:12:45

问题


I have two edit text views. If I click first, I need to select first edittext and set to second "00". Like in default android alarm clock. My problem:

  • I have api level 10, so I can't write something like:

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

If I use

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

so I need click my view twice. Possible solution:

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

so my .setSelection does not always work. OMG! Help me please


回答1:


If I understood correctly, you want to do the following:

  • When focusing firstEText, select all the text within firstEText and set secondEText to "00".

What I don't understand is why you say you cannot use setOnFocusChangeListener, since, it is available since API 1.

A convenient attribute to select all the text of an EditText when getting focus on an element, is android:selectAllOnFocus, which does exactly what you want. Then, you just need to set secondEText to "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" />

Activity

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

});

Hope it helps.



来源:https://stackoverflow.com/questions/17413479/android-edittext-onclick-event-handling-and-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!