Android Studio 如何在TextView中設置圖標並按需調整圖標大小


 

•任務

  

  相信大家對這張圖片都不陌生,沒錯,就是 QQ動態 向我們展示的界面。

  如何實現呢?

•添加文字並放入圖標

  新建一個 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 中圖片的大小,所以,這張效果圖就將就着看一下吧,哈哈哈。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM