Search code examples
androidxmlandroid-edittextcustomizationprogrammatically-created

Define a Custom EditText


I'm a beginner. I want to define the xml for a custom EditText and then programmatically add those custom edittexts at runtime without using a bunch of code to customize the editTexts. This could be similar to implementing custom buttons, textviews, etc. from libraries...although it would be my own. What is the best way to approach this?

Thanks!


Solution

  • Alternative code apart from code shared in above comment link is below : basically this code makes easy for user to customize the fonts etc.

    public class MyEditText extends EditText {
    
        public MyEditText(Context context) {
            super(context);
        }
    
        public MyEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            parseAttributes(context, attrs);
        }
    
        public MyEditText(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            parseAttributes(context, attrs);
        }
    
        private void parseAttributes(Context context, AttributeSet attrs) {
            TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.Simplified);
    
            int typefaceValue = values.getInt(R.styleable.Simplified_typeface, 0);
            values.recycle();
    
            setTypeface(MyFontUtil.obtaintTypeface(context, typefaceValue));
        }
    
    }
    

    XML

     <com.my.mtetno.widget.MyEditText
      android:id="@+id/uname"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:background="@drawable/lh_edit_field_without_border"
      android:inputType="textEmailAddress"
      android:maxLines="1"
      android:overScrollMode="always"
      android:textSize="@dimen/login_page_edit_text_size"
      app:typeface="simplified_regular" />