How to auto size textview dynamically according to the length of the text in android?

前端 未结 7 797
不思量自难忘°
不思量自难忘° 2021-02-04 07:07

I am taking data of variable sizes from the server and setting to a textView and i wanted the textview to resize according to the length of the text set.

It is given in

7条回答
  •  野的像风
    2021-02-04 07:34

    addTextChangedListener is a listener for Edit Tex. this listener watch the changes of editText and it has three different states.

    EditText edt = someEditText;
    edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            /*watch the editText on every input and changes, then mange the size by if statements and editText length*/
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (edt.getText().toString().length() > 10){
                    edt.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeSmall);
                }
                else if (edt.getText().toString().length() > 5){
                    edt.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeMedium);
                }
            }
    
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    

    Updated: According to question 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) {
    
            }
        });
    }
    

    }

    you must use it in xml instead of the usual textView

提交回复
热议问题