2

I am trying to resize a textbox dynamically using Java code. I want the width to not use wrap content but using a static number in dp. I want this to be done in Java code instead of the XML file. I want it like this is because I want to apply it to each item in the recyclerview. It needs to work with multiple screens sizes. It will work like a min Length for a textfield box size. If you know how to do this would be much appericaiated.

M.Dunne
  • 21
  • 2
  • 3
    Does this answer your question? [Android set height and width of Custom view programmatically](https://stackoverflow.com/questions/5042197/android-set-height-and-width-of-custom-view-programmatically) – Gk Mohammad Emon Oct 06 '20 at 11:59

1 Answers1

0

this is called auto sizing and it can be done by adding TextChangedListener which is a listener for Edit Tex. this listener watch the changes of editText and it has three different states. also you can create a component(custom view) and extend it from AppCompatTextView name as you want; in its initialization you can add below code:

public class CustomTextView extends AppCompatTextView {
Context ctx;

public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
ctx = context;
init();
}

public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
ctx = context;
init();
}

public CustomTextView(Context context) {
super(context);
ctx = context;
init();
}

  public void init() {
setOnTouchListener(null);
addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int  count) {
        if (getText().toString().length() > 10){
            setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeSmall);
        }
        else if (getText().toString().length() > 5){
            setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeMedium);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

}

also check these out, there is a tone of documentation for it:

Autosizing TextView Tutorial for Android

Autosizing TextViews

narcis dpr
  • 939
  • 2
  • 12
  • 32