Selecting an Android EditView's text when it gets focus?
I have a view that contains a number of EditViews. When one is selected, I want all of its text to be selected, rather than just having the edit cursor appear. What I try is this:
EditText E = new EditText(this);
E.setRawInputType(InputType.TYPE_CLASS_NUMBER);
E.setImeOptions(EditorInfo.IME_ACTION_DONE);
E.setText("Some Text");
E.setOnFocusChangeListener(
new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
{
// Set the selection to the entire text
EditText E2 = (EditText) v;
E2.setSelection(0, E2.getText().length());
}
}
}
);
When I select an EditText, onFocusChange is being called with hasFocus = true, but the text is not being selected; instead, the edit cursor appears as it usually does.
Also, when I include this line before the setSelection call:
E2.setText("Changed");
it sets the text to "Changed" successfully, but still doesn't select the text.
Also, if I use setSelected immediately after the initial E.setText call, the text in the EditText that has the initial focus is selected.
How do I select an EditView's text within an onFocusChangeListener.onFocusChange call?
Itzik Samara回答的问题(“使用setSelectAllOnFocus(布尔)”)在原始问题的评论 - 这是添加的,所以问题可以被标记为回答
You can do three things here:
If you prefer to do this programatically:
1) You can call setSelectAllOnFocus(Boolean) before you call the OnFocusChangeListener(), eg:
E.setSelectAllOnFocus(true);
2) Inside the hasFocus conditional, you can say
E.selectAll();
If you would rather use your XML Layout :
3) You can apply setSelectAllOnFocus on your EditText field in your layout, like:
android:selectAllOnFocus="true"
Hope that helps !
链接地址: http://www.djcxy.com/p/24210.html