Search code examples
androidgridviewlayoutlayoutparamsgetview

Error while compiling android example for GridView


Im trying to write a simple adapter for GridView exactly from google example for GridView ; here's my getView function .

public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;

        if (convertView == null) {
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridLayout.LayoutParams(120,120));
            imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setPadding(2, 2, 2, 2);
        }
        else
        {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

but I get some error like this for this line imageView.setLayoutParams(new GridLayout.LayoutParams(120,120));

Error:(39, 39) error: no suitable constructor found for LayoutParams(int,int)
constructor android.widget.GridLayout.LayoutParams.android.widget.GridLayout.LayoutParam (Context,AttributeSet) is not applicable
(actual argument int cannot be converted to Context by method invocation conversion)
constructor android.widget.GridLayout.LayoutParams.android.widget.GridLayout.LayoutParams(android.widget.GridLayout.LayoutParams) is not applicable
(actual and formal argument lists differ in length)
constructor android.widget.GridLayout.LayoutParams.android.widget.GridLayout.LayoutParams(MarginLayoutParams) is not applicable
(actual and formal argument lists differ in length)
constructor android.widget.GridLayout.LayoutParams.android.widget.GridLayout.LayoutParams(android.view.ViewGroup.LayoutParams) is not applicable
(actual and formal argument lists differ in length)
constructor android.widget.GridLayout.LayoutParams.android.widget.GridLayout.LayoutParams() is not applicable
(actual and formal argument lists differ in length)
constructor android.widget.GridLayout.LayoutParams.android.widget.GridLayout.LayoutParams(Spec,Spec) is not applicable
(actual argument int cannot be converted to Spec by method invocation conversion)

Is there any solution ?


Solution

  • check the following code:

    import android.widget.GridLayout.LayoutParams;//import this statement
    
    int dp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120, getResources().getDisplayMetrics()); 
    imageView.setLayoutParams(new LayoutParams(dp, dp));//120dp