Android drawableTopピクチャサイズの設定


開発ではTextView、Button、RadioButtonの3つのコントロールをよく使用しています.多くの場合、文字と画像を一緒に表示する必要があります.多くのアプリケーションの下部のナビゲーションバーはRadioGroupで切り替え機能を実現しています.例えばQQなどです.この場合、RadioButtonのdrawableTop、drawableLeft、drawableRight、drawableBottomの4つの属性値を使って、文字の対応方向の画像を設定します.ただし、画像サイズの属性値は設定されていません.これらの画像のサイズを設定するのは簡単ですが、次の方法について説明します.
  • getCompoundDrawables()このメソッドは、コントロールの左、上、右、下の4つの位置を含むDrawableの配列
  • を返します.
  • setBounds(left,top,right,bottom)drawableの境界
  • を指定
  • setCompoundDrawables(drawableLeft,drawableTop,drawableRight,drawableBottom)設定コントロール左、上、右、下の4つの位置のDrawable
  • Button、RadioButtonは実はすべてTextViewのサブクラスで、この3つの方法はすべてTextViewの中の方法です
    まずコントロールの上のdrawableを手に入れ、drawableの境界を指定し、最後にdrawableを設定します.
    この例はRadioGroupには5つのRadioButtonがあり、それぞれdrawableTopピクチャがあります.
        /**
         *       
         */
        public void initButton(){
            for (int i = 0; i < radioIds.length; i++) {//  
    
                drawables = radioBtns[i].getCompoundDrawables();//  RadioButton getCompoundDrawables()  ,     drawables,          
    
                switch (i) {//    drawableTop    setBounds(left,top,right,bottom)
                case 0:
                    drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x18),
                            getResources().getDimensionPixelSize(R.dimen.x24));
                    break;
    
                case 1:
                    drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x25),
                            getResources().getDimensionPixelSize(R.dimen.x25));
                    break;
                case 2:
                    drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x40),
                            getResources().getDimensionPixelSize(R.dimen.x25));
                    break;
                case 3:
                    drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x25),
                            getResources().getDimensionPixelSize(R.dimen.x25));
                    break;
                case 4:
                    drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x25),
                            getResources().getDimensionPixelSize(R.dimen.x25));
                    break;
                default:
                    break;
                }
    
                radioBtns[i].setCompoundDrawables(drawables[0], drawables[1], drawables[2],
                        drawables[3]);//       drawable       
            }
            radioBtns[0].setChecked(true);
        }