网上一搜全是自定义控件,其实不用那么麻烦,解决这个问题,直接xml文件中就能搞定,代码如下:
<TextView
android:id="@+id/display_translation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/btn_green_side"
android:text="隐藏翻译"
android:textSize="21sp"
android:textColor="#01B9FF"
android:layout_marginRight="26dp"
android:drawableLeft="@drawable/icon_xsfy"
android:drawablePadding="9dp"
android:paddingLeft="25dp"
android:paddingRight="25dp"
android:paddingTop="12dp"
android:paddingBottom="12dp"/>
其实代码很简单,就是利用 padding 内边距 使 图片和文字居中就可以了。
效果图如下:
TextView动态设置旁边图片,可使用如下代码:
TextView textView = (TextView)findViewById(R.id.display_translation);
Drawable drawable= getResources().getDrawable(R.drawable.icon_xsfy);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//这句一定要加
textView.setCompoundDrawables(drawable,null,null,null);//setCompoundDrawables用来设置图片显示在文本的哪一端