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
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.