In my case, this is because when the ListView resizes, it re-creates all the items in the list (i.e., it calls getView () again for each item in the visible list).
Since EditText is in the layout I am returning from getView (), this means that it is a different instance of EditText than the one that previously had focus. The second corollary is that when the soft keyboard appears or disappears, I find that I am losing the contents of the EditText.
Because I wanted my view to remain fully accessible (i.e. I want it to be changed, not hidden behind the keyboard window, and some parts not available), I could not use Frank's answer, which otherwise seems the best.
I solved this using OnFocusChangeListener in EditText to write the timestamp when the focus was lost, and then in getView () when recreating the list item, if the current time is within some threshold when the focus was lost, call requestFocus () to return it to the EditText in question.
You can also grab text from a previous EditText instance at this point and transfer it to a new instance.
private class MyAdapter<Type> extends ArrayAdapter<String> implements OnFocusChangeListener { private EditText mText; private long mTextLostFocusTimestamp; private LayoutInflater mLayoutInflater; public MyAdapter(Context context, int resource, int textResourceId, ArrayList<String> data, LayoutInflater li) { super(context, resource, textResourceId, data); mLayoutInflater = li; mTextLostFocusTimestamp = -1; } private void reclaimFocus(View v, long timestamp) { if (timestamp == -1) return; if ((System.currentTimeMillis() - timestamp) < 250) v.requestFocus(); } @Override public View getView (int position, View convertView, ViewGroup parent) { View v = mLayoutInflater.inflate(R.layout.mylayout, parent, false); EditText newText = (EditText) v.findViewById(R.id.email); if (mText != null) newText.setText(mText.getText()); mText = newText; mText.setOnFocusChangeListener(this); reclaimFocus(mText, mTextLostFocusTimestamp); return v; } @Override public void onFocusChange(View v, boolean hasFocus) { if ((v == mText) && !hasFocus) mTextLostFocusTimestamp = System.currentTimeMillis(); } }
sheltond Oct 24 '13 at 15:39 2013-10-24 15:39
source share