【问题标题】:Dynamic Resizing Android Studio TextView [duplicate]动态调整 Android Studio TextView [重复]
【发布时间】:2021-01-21 07:11:11
【问题描述】:

我正在尝试使用 Java 代码动态调整文本框的大小。我希望宽度不使用换行内容,而是在 dp 中使用静态数字。我希望用 Java 代码而不是 XML 文件来完成。我想要这样是因为我想将它应用于 recyclerview 中的每个项目。它需要使用多种屏幕尺寸。它将像文本框大小的最小长度一样工作。如果您知道如何执行此操作,将非常有用。

【问题讨论】:

标签: java android xml dynamic


【解决方案1】:

这称为自动调整大小,可以通过添加 TextChangedListener 来完成,它是 Edit Tex 的侦听器。此侦听器监视 editText 的变化,它具有三种不同的状态。您也可以创建一个组件(自定义视图)并根据需要从 AppCompatTextView 名称扩展它;在其初始化中,您可以添加以下代码:

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) {

    }
});

}

也检查这些,有一个文档的基调:

Autosizing TextView Tutorial for Android

Autosizing TextViews

【讨论】:

    【解决方案2】:

    我想这会对你有所帮助..

    LinearLayout.LayoutParams textParam = new LinearLayout.LayoutParams
                        (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
    
    textView.setLayoutParams(textParam);
    

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      相关资源
      最近更新 更多