【问题标题】:How to set multiple TextView's size如何设置多个TextView的大小
【发布时间】:2017-12-22 07:21:35
【问题描述】:

我在ViewHolder 中有很多TextView's
喜欢:

holder.ID1 = (TextView) vi.findViewById(R.id.lbID1);
holder.ID2 = (TextView) vi.findViewById(R.id.lbID2);
holder.ID3 = (TextView) vi.findViewById(R.id.lbID3);
holder.ID4 = (TextView) vi.findViewById(R.id.lbID4);  and so on....

属性和大小在style.xmldimens.xml 中定义。现在我想根据 Small、 MediumLarge 等设置设置大小。这是我在登录时收到的Integer 值,但我知道

无法通过我的activity 以编程方式设置我的dimen.xml 文件中的dimen 变量的值。

所以一种方法是像这样设置大小:

setSize(holder.ID1, Size);   
setSize(holder.ID2, Size);
setSize(holder.ID3, Size);
setSize(holder.ID4, Size); and so on....


public void setSize(TextView textView, int size) {
    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, size);
}

这是一个漫长的过程。还有其他SortGood的方法吗???

【问题讨论】:

  • 只需使用 dimens.xml 并在 xml 中设置文本大小。或者您可以为每个文本视图使用样式,例如 smallStyle、largeStyle 等。'
  • 但在登录时我收到了整数值的大小。那么我如何在 style.xml 或 dimens.xml 中使用 if 条件
  • 然后使用TypedValue.COMPLEX_UNIT_SP .setTextSize 只是一个代码,您需要在每个视图上调用它,所以我认为您可以单独调用它。不需要实用程序类。

标签: android


【解决方案1】:

我建议你使用自定义TextView

CustomTextView.java

public class CustomTextView extends android.support.v7.widget.AppCompatTextView {

String Size;

public CustomTextView(Context context) {
    super(context);
}

public CustomTextView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView,0,0);

    try{

        Size = ta.getString(R.styleable.CustomTextView_ctv_size);

        if (Size.equals("small")){

            this.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        }else{
            this.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);

        }

    }finally {
        ta.recycle();
    }

}

public CustomTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}
 }

attr.xml 文件添加到您的 values 目录,并在其中添加以下代码:

 <declare-styleable name="CustomTextView">
        <attr name="ctv_size" format="string"/>
 </declare-styleable>

然后将其用作 XML 中的视图

  <com....CustomTextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:ctv_size="small"/>

它将正常工作且顺利...干杯....

【讨论】:

  • 您可以使用其他选项,例如 medium 和 big... 对于所有这些,您可以设置其他 textview 大小值...
【解决方案2】:
  1. 编写一个辅助函数来接受持有者和大小。
  2. 然后在辅助函数中搜索循环中的每个孩子。
  3. 如果子视图是 TextView,则将其转换为 TextView 并调用 setTextSize 函数,并在步骤 1 中的帮助程序中传递大小。

【讨论】:

  • 这可行,但不适合,因为 OP 想要一个简短的解决方案,而不必处理每个文本视图。
  • 他不必处理每个文本视图。只写一次。在循环中,代码在每个 textview 上执行
猜你喜欢
  • 2016-06-18
  • 1970-01-01
  • 2020-03-01
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 2015-06-11
相关资源
最近更新 更多