图标简化实现"/>
Android之TextView文字旁边有图标简化实现
在开发过程中,经常会遇到下图的情况
文字旁边有图标,如果将文字和图片用两个控件来实现就比较麻烦了,简单的方式就是用一个TextView来实现
TextView text = new TextView(getContext());
text.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.picture1),null,null,null);//依次是左、上、右、下,有就是位置,没有就是null
text.setCompoundDrawablePadding(30);//设置文字与图标间距
今天遇到一个比较麻烦的情况,效果如下
文字和图片在一个高度,但相对于背景来说并不是居中,所以不能用常用的居中来实现。所以我就想向从margin和padding入手,但是会发现文字和图片的顶部/底部会在一个高度,并且不能单独设置文字和图片的topMargin/topPadding,所以这个方法也放弃了。因为不想将文字和图标用两个控件实现,所以就想了下面的办法,在textView下面放一个FramLayout,并设置一个topPadding,值为刚好能够使下面的居中显示
public class VoiceBoxView extends FrameLayout {TextView text;public VoiceBoxView(Context context){super(context);setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));setBackgroundResource(R.drawable.voice_box_bg);setPadding(0,9,0,0);//将上面的宽度加入layout的padding,下面的textView就可以居中啦text = new TextView(context);text.setSingleLine(true);text.setTextSize(24);text.setTextColor(getResources().getColor(R.color.c_1));text.setText("语音呼出 “请帮我开启洗衣机的什模式” ");text.getPaint().setFakeBoldText(true);text.setGravity(Gravity.CENTER_VERTICAL);text.setPadding(0,8,0,8);//保证图片的上下间距text.setCompoundDrawablePadding(10);text.setCompoundDrawablesWithIntrinsicBounds(null, null,getResources().getDrawable(R.drawable.voice_box_icons),null);FrameLayout.LayoutParams textLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);textLayoutParams.leftMargin = 24;textLayoutParams.rightMargin = 8;textLayoutParams.gravity = Gravity.CENTER_VERTICAL;text.setSingleLine(true);addView(text, textLayoutParams);}
}
更多推荐
Android之TextView文字旁边有图标简化实现
发布评论