setCompoundDrawables和setCompoundDrawablesWithIntrinsicBounds區別


  前言:今天看源碼看到的setCompoundDrawablesWithIntrinsicBounds方法當時初步理解就是在view的不同方向設置drawable圖像,上網上查了查,就發現還有一個

setCompoundDrawables的方法。手工設置文本與圖片相對位置時,比如edittext中的設置左邊圖像或者右邊圖像一樣,這里就來說說他們的區別

  他們都是TextView的方法,如果不設置就可以在相應的參數位置上設置為null

  1.setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)

   <1>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)。意思是你要添加的資源必須已經設置過初始位置、寬和高等信息。

  這下就明白了,這個方法要先給Drawable設置setBounds(x,y,width,height);

    x:組件在容器X軸上的起點

    y:組件在容器Y軸上的起點

    width:組件的長度

    height:組件的高度。

  <2>用法

1 mBtn = (Button) findViewById(R.id.id_btn);
2         Drawable icon = this.getResources().getDrawable(R.drawable.ic_launcher);
3         // 必須設置
4         icon.setBounds(1, 1, 100, 100);
5         mBtn.setCompoundDrawables(null, null, icon, null);

   效果:

     

  2.setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom)

  <1>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' bounds will be set to their intrinsic bounds.

意思大概就是:可以在上、下、左、右設置圖標,如果不想在某個地方顯示,則設置為null。圖標的寬高將會設置為固有寬高,既自動通過getIntrinsicWidth和getIntrinsicHeight獲取。

  <2>用法

1     mBtn = (Button) findViewById(R.id.id_btn);
2         Drawable icon = this.getResources().getDrawable(R.drawable.ic_launcher);
3         mBtn.setCompoundDrawablesWithIntrinsicBounds(null, null, icon, null);

   效果

 


免責聲明!

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



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