Search code examples
javaandroidandroid-view

Android edittext underline missing when background is set


I want to set a background of dynamically created edittext and to have its underline at the same time. Now it has a background, but it does not have underline. When I remove setBackground() then underline is shown.

I tried a constructor of edittext like that but it didn't help: etTitle = new EditText(new ContextThemeWrapper(fragment.requireContext(), R.style.editText));

I don't want transparency on this background.

                etTitle = new EditText(fragment.requireContext());
                etTitle.setId(Util.getIdNotUsed(fragment.requireActivity()));

                TypedArray a = fragment.requireActivity().getTheme().obtainStyledAttributes(isDarkMode ? R.style.notepad_dark : R.style.notepad_light, new int[] {R.attr.myColorBottomNavigationViewBg});
                int attributeResourceId = a.getResourceId(0, 0);
                Drawable drawable = ContextCompat.getDrawable(fragment.requireContext(), attributeResourceId);

                etTitle.setBackground(drawable);

How to solve that?


Solution

  • Android EditText underline is typically a part of the default background drawable. Setting a new background drawable would naturally override it and to work that around I'd go for layered drawable, which allows to stack multiple drawables on top of each other. That way you'd have both your custom background and the default underline, and then set that as the background of your EditText (of course you can create your drawable from code as well):

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <color android:color="@color/your_background_color"/>
        </item>
        <item>
            <bitmap
                android:gravity="bottom"
                android:src="@drawable/your_underline_image" />
        </item>
    </layer-list>
    

    Then use it in your code

    Drawable layeredDrawable = ContextCompat.getDrawable(fragment.requireContext(), R.drawable.your_layered_drawable);
    etTitle.setBackground(layeredDrawable);