Android之TextView文字旁边有图标简化实现

编程入门 行业动态 更新时间:2024-10-04 05:24:47

Android之TextView文字旁边有<a href=https://www.elefans.com/category/jswz/34/1769937.html style=图标简化实现"/>

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文字旁边有图标简化实现

本文发布于:2024-02-19 15:13:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1764382.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图标   文字   Android   TextView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!