【问题标题】:Custom TextView Padding, TextSize Attributes Not Working自定义 TextView 填充、TextSize 属性不起作用
【发布时间】:2015-01-27 10:22:24
【问题描述】:

所以我正在尝试创建一个扩展原生 TextView 的自定义 textView。但是,当我在片段中对其进行膨胀时,尽管背景等属性正在工作,但填充和 textSize 等属性却不起作用。即使我以编程方式将它们添加到构造函数中,它们也不起作用。我一定错过了一些微不足道的东西。请帮忙。

自定义视图

public class TextBox extends TextView{

    private OneTimeTask oneTimeTask;
    private Integer oneTimeTaskId;

    public TextBox (Context context) {
        super(context);
        appearance();

    }

    public TextBox (Context context, AttributeSet attrs) {
        super(context, attrs);
        appearance();
    }

public TextBox (Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    appearance();
}

    public void  appearance(){
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
            this.setLayoutParams(params);
            this.setTextSize(getResources().getDimension(R.dimen.material_micro_text_size));
            this.setPadding((int) getResources().getDimension(R.dimen.material_padding),(int) getResources().getDimension(R.dimen.material_small_padding),(int) getResources().getDimension(R.dimen.material_padding),(int) getResources().getDimension(R.dimen.material_small_padding));
            this.setGravity(Gravity.CENTER_VERTICAL);
            this.setTextColor(getResources().getColor(R.color.white));
            this.setText("Not Started");
   }
 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }
}

Xml

<com.me.p.k.TextBox 

    xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="Test"
        android:id="@+id/state"
        android:textSize="10sp"
        android:gravity="bottom"
        android:paddingRight="16dp"
        android:paddingLeft="16dp"
        android:textColor="@color/white"
        android:background="@color/pink"
        android:paddingTop="16dp"
        android:paddingBottom="16dp" />

编辑

添加了 Karakuri 的部分建议。

【问题讨论】:

    标签: android textview


    【解决方案1】:

    添加三参数构造函数。

    public TextBox (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        appearance();
    }
    

    另外,我不会同时在代码和 XML 中设置属性,因为它只是令人困惑。选择一个或另一个 - 到目前为止,我看到的所有内容都可以通过定义样式资源并将其应用于视图来设置。

    【讨论】:

      猜你喜欢
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      相关资源
      最近更新 更多