I have an Activity
in Android, with two elements:
EditText
ListView
When my Activity
Being that I don't like to pollute the XML with something that is related to functionality, I created this method that "transparently" steals the focus from the first focusable view and then makes sure to remove itself when necessary!
public static View preventInitialFocus(final Activity activity)
{
final ViewGroup content = (ViewGroup)activity.findViewById(android.R.id.content);
final View root = content.getChildAt(0);
if (root == null) return null;
final View focusDummy = new View(activity);
final View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View view, boolean b)
{
view.setOnFocusChangeListener(null);
content.removeView(focusDummy);
}
};
focusDummy.setFocusable(true);
focusDummy.setFocusableInTouchMode(true);
content.addView(focusDummy, 0, new LinearLayout.LayoutParams(0, 0));
if (root instanceof ViewGroup)
{
final ViewGroup _root = (ViewGroup)root;
for (int i = 1, children = _root.getChildCount(); i < children; i++)
{
final View child = _root.getChildAt(i);
if (child.isFocusable() || child.isFocusableInTouchMode())
{
child.setOnFocusChangeListener(onFocusChangeListener);
break;
}
}
}
else if (root.isFocusable() || root.isFocusableInTouchMode())
root.setOnFocusChangeListener(onFocusChangeListener);
return focusDummy;
}