How to stop EditText from gaining focus at Activity startup in Android

后端 未结 30 2772
别那么骄傲
别那么骄傲 2020-11-21 06:40

I have an Activity in Android, with two elements:

  1. EditText
  2. ListView

When my Activity

30条回答
  •  醉梦人生
    2020-11-21 07:10

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

提交回复
热议问题