问题场景
在实现图案和文字左右对齐时,我一开始很喜欢用DrawableLeft和DrawableRight属性来实现,比较简单,但是由于不能它不能通过xml来实现对图片大小的管理,往往需要使用Java代码的配合,会对以后代码的维护造成困难。
通过DrawableLeft 来实现
<TextView
android:id="@+id/timelock_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="时间锁 40分钟"
android:textSize="16dp"
android:textColor="@color/message_record_button_text_color"
android:gravity="center" />
txtTimeLock =(TextView)findViewById(R.id.timelock_text);
Drawable timeLockLeft = getResources().getDrawable(R.drawable.young_icon_timelock);
timeLockLeft.setBounds(0,0,40,40);
txtTimeLock.setCompoundDrawables(timeLockLeft,null,null,null);
因此采用相对布局来实现图案和文字的左右对其,则不需要Java代码的配合,但是其对其方式需要考虑,因为默认的TextView有自己的Padding,而ImageView并没有padding ,为了实现其对齐,我选择了使用layout_alignBaseline
来对其,但是其默认的方式是ImageView顶部和其BaseLine 对其,因此要搭配使用baselineAlignBottom
,但是有时也会看起来那么不协调,因此采用baseLine
来相对于BaseLine对齐,看一下效果:
baseLine=“13dp”
android:baselineAlignBottom=“true”
因为相差只有3dp,效果不太明显,但是如果要求精度高的话,可以注意一下这两个变化。
两个标签属性的作用:
baselineAlignBottom:使ImageView的底部和基线对齐
baseline:View相对于基线的偏移量
附上用相对布局实现图案和文字左右对齐的源码:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:gravity="center_vertical"
android:layout_marginBottom="20dp">
<ImageView
android:id="@+id/timelock_img"
android:layout_width="12dp"
android:layout_height="12dp"
android:layout_alignBaseline="@+id/timelock_text"
android:layout_marginRight="2dp"
android:baselineAlignBottom="true"
android:src="@drawable/young_icon_timelock" />
<TextView
android:id="@+id/timelock_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="时间锁 40分钟"
android:textSize="16dp"
android:textColor="@color/message_record_button_text_color"
android:gravity="center"
android:layout_toRightOf="@+id/timelock_img" />
<TextView
android:layout_below="@+id/timelock_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="单日使用时长超过40分钟将需要输入密码方可继续使用"
android:textColor="@color/common_gray_63"
android:textSize="13dp"
android:paddingLeft="20dp"
android:layout_marginTop="4dp"/>
</RelativeLayout>