添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

•添加文字并放入图标

新建一个 Activity,取名为 QQ,Android Studio 自动为我们生成了两个文件: QQ.java 和 activity_q_q.xml。

从网上下载 QQ空间图标,图片及信息如下:

我将该图片保存在了 res/drawable 文件夹下,并命名为 qq.jpg。

在 activity_q_q.xml 中通过 TextView 控件将 “好友动态” 这四个字以及图标加入,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">
    <TextView
        android:id="@+id/tv_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/qq"
        android:text="好友动态"
        android:textColor="#000000"
        android:textSize="25sp"
        android:textStyle="bold" />
</LinearLayout>

通过 drawableLeft 属性将图片放置在了文字的左侧,你以为这样就大功告成了吗?

没有实践就没有发言权,让我们来运行一下,看看结果如何。

•效果展示图

你会发现,图片过于大了,占据了整个屏幕还没有显示完。

那么,接下来,我们需要做的就是,调整图片大小,使其能够按照我们的预想展示出来。

•调整图标大小

在 QQ.java 文件中,我们通过 setBounds()方法 和 setCompoundDrawables()方法 来调整图标大小。

具体代码如下:

public class QQ extends AppCompatActivity {
    private TextView tv1;
    Drawable icon;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_q_q);
        tv1 = findViewById(R.id.tv_1);
        icon = getResources().getDrawable(R.drawable.qq);
        icon.setBounds(0, 0, 80, 80);
        tv1.setCompoundDrawables(icon, null, null, null);

  setBounds(left , top , right , bottom) 方法中共有四个参数:

  • 前两个是组件左上角在容器中的坐标
  • 后两个是组件的宽度和高度
  •   这个是我在百度上找的,原文链接

      我自己也测试了一下,大致差不多,但是对前两个参数还存在疑问,在不改变后两个参数的情况下,该边前两个参数,图片大小发生变化,也不知道为啥,留着以后解决。

      还有一种解释是 right-left = drawable 的宽,top - bottom = drawable 的高,原文链接

      setCompoundDrawables(left , top , right , bottom) 方法中同样有四个参数,API 原文为:

    Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. 
    The Drawables must already have had setBounds(Rect) called.
    意思大概就是:可以在上、下、左、右设置图标,如果不想在某个地方显示,则设置为null。但是Drawable必须已经setBounds(Rect)。
    意思是你要添加的资源必须已经设置过初始位置、宽和高等信息。

      原文链接

      任务图中QQ图标在文字的左侧,所以,将 left 位置设置为 icon,其他位置设置为 null 即可。

    •效果展示图

      本节所讲的主要内容是如何调整 TextView 中图片的大小,所以,这张效果图就将就着看一下吧,哈哈哈。