Using ImageView as background for an Android Layout

前端 未结 2 2019
南笙
南笙 2021-02-09 03:20

I want to take advantage of the scaleType property, which I cannot use if I set my image using the background property on the LinearLayout. I\'ve tried using a

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-09 04:01

    I cannot use above because of I have adapter and images are set from their to display in GridView. So, in 2019 Im doing like below:

    
    
        
    
        
    
    

    The key attribute for Stacking view here is android:layout_centerInParent="true".

    Also note that I created android:background="@drawable/shape_image_holder_text" to get some corner radius around my text view with some backdrop. Here is that xml:

    
    
        
            
                
                
                
            
        
    
    

    To make my image adjust to height and width to same size in GridView. I created a custom class for SquareImageView(You can use default ImageView if you are not using GridView or if you don't care about this).

    My SquareImageView.java file:

    import android.content.Context;
    import android.support.v7.widget.AppCompatImageView;
    import android.util.AttributeSet;
    
    public class SquareImageView extends AppCompatImageView {
    
        public SquareImageView(Context context) {
            super(context);
        }
    
        public SquareImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            //noinspection SuspiciousNameCombination
            super.onMeasure(widthMeasureSpec, widthMeasureSpec);
        }
    
        public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    }
    

    It look like this:

提交回复
热议问题