Setting a background image to a view stretches my view

前端 未结 7 2087
梦如初夏
梦如初夏 2020-12-05 17:54

I created a background image bitmap for a view and now the view is being stretched to the size of the background image....

is this normal?



        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 17:57

    One good solution that is working perfectly in my case is extending the View and overriding onMeasure().

    Here is the steps to do:

    1. Create an own class and extend the View you want to use, here for example I will use Button.
    2. Override the method onMeasure() and insert the code at the bottom. This will set the background resource after the first measure has been done. For the second measure event, it will use the already measured paramters.

    Example code for a custom view which extends Button (change Button to the View you would like to extend)

    public class MyButton extends Button {
    
        boolean backGroundSet = false;
    
        public MyButton(Context context) {
            super(context);
        }
    
        public MyButton(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);          
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
            if(backGroundSet) {
                setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
                return;
            }
    
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
            backGroundSet = true;
            setBackgroundResource(R.drawable.button_back_selector);
    
        }
    }
    

    The only thing to change here is the type of view you want to extend and in the onMeasure() method the background resource you want to use for the view.

    After that, just use this view in your layout xml or add it programatically.

提交回复
热议问题