发表于: 2018-11-06 23:41:28

0 683


一、今天完成的事情

 今天发现自定控件中的文字大小无法通过dimension属性准确设置

自定义属性,其中content_text_size定义的是文本的尺寸,类型是dimension

<declare-styleable name="twoTextViews" >
   <attr name="title_text_1" format="string" />
   <attr name="content_text" format="string" />
   <attr name="title_text_color" format="color" />
   <attr name="content_text_color" format="color" />
   <attr name="content_text_size" format="dimension" />
</declare-styleable>

设置属性

contentTextSize = typedArray.getDimensionPixelSize(

       R.styleable.twoTextViews_content_text_size, 16);

contentTV.setTextSize(contentTextSize);

使用属性

<com.example.forrestsu.logintest.my_controls.TwoTextViewsControl
   android:id="@+id/my_control_introduction"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_marginStart="30dp"
   android:layout_marginTop="14dp"
   android:layout_marginEnd="30dp"
   android:maxHeight="100dp"
   app:layout_constraintEnd_toEndOf="parent"
   app:layout_constraintStart_toStartOf="parent"
   app:layout_constraintTop_toBottomOf="@+id/view_line_4"
   twoTextViews:content_text_size="14"/>

结果文字的大小并不是预期的大小,查了以后发现    在代码中getDimension 获取的这个值并不是我们在属性中设置的值,而是根据不同手机分辨率和dpi的到的,所以在不同的手机上会出现不同的大小。

解决方法,重新定义一个属性已sp为单位去设置文字的尺寸。

<declare-styleable name="twoTextViews" >
   <attr name="title_text_1" format="string" />
   <attr name="content_text" format="string" />
   <attr name="title_text_color" format="color" />
   <attr name="content_text_color" format="color" />
   <attr name="title_text_size" format="dimension" />
   <attr name="content_text_size" format="integer" />
</declare-styleable>

这里将content_text_size的类型设为了integer,这样可以保证使用这个属性时设置的值不会变化,然后还需要一个单位sp,在代码中设置。

contentTextSize = typedArray.getInteger(R.styleable.twoTextViews_content_text_size, 16);
contentTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, contentTextSize);

这里用到了单位转换函数TypeValue

这样文字就会显示为以sp为单位的大小了。


二、明天计划的事情

      在地图上查看附近的护工、雇主位置


三、遇到的问题

    

四、收获

   TypeValue

下一篇



返回列表 返回列表
评论

    分享到