为什么我不能调用getActivity()?

时间:2015-07-31 18:08:05

标签: java android android-layout android-fragments android-activity

所以我试图在一个片段中实现一个库,在我自己进行一些修改之后会进行一些修改。但是我似乎无法在我的代码中调用getActivity():

这是GalleryFragment类:

public class GalleryFragment extends Fragment {

    private Utils utils;
    private ArrayList<String> imagePaths = new ArrayList<String>();
    private GridViewImageAdapter adapter;
    private GridView gridView;
    private int columnWidth;


    public GalleryFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       // View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
        //Inflate the layout for this fragment
       // return rootView;
        View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
        GridView gridView = (GridView) rootView.findViewById(R.id.grid_view);

        // Instance of ImageAdapter Class
        gridView.setAdapter(new GridViewImageAdapter(getActivity()));
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {

                // Sending image id to FullScreenActivity
                Intent i = new Intent(getActivity(), FullScreenViewActivity.class);
                // passing array index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void InitilizeGridLayout() {
        Resources r = getResources();
        float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                AppConstant.GRID_PADDING, r.getDisplayMetrics());

        columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);

        gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
        gridView.setColumnWidth(columnWidth);
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setPadding((int) padding, (int) padding, (int) padding,
                (int) padding);
        gridView.setHorizontalSpacing((int) padding);
        gridView.setVerticalSpacing((int) padding);
    }

}

这是GridViewImageAdapter:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;


    public class GridViewImageAdapter extends BaseAdapter {

        private Activity _activity;
        private ArrayList<String> _filePaths = new ArrayList<String>();
        private int imageWidth;

        public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
                                    int imageWidth) {
            this._activity = activity;
            this._filePaths = filePaths;
            this.imageWidth = imageWidth;
        }

        @Override
        public int getCount() {
            return this._filePaths.size();
        }

        @Override
        public Object getItem(int position) {
            return this._filePaths.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(_activity);
            } else {
                imageView = (ImageView) convertView;
            }

            // get screen dimensions
            Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
                    imageWidth);

            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
                    imageWidth));
            imageView.setImageBitmap(image);

            // image view click listener
            imageView.setOnClickListener(new OnImageClickListener(position));

            return imageView;
        }

        class OnImageClickListener implements OnClickListener {

            int _postion;

            // constructor
            public OnImageClickListener(int position) {
                this._postion = position;
            }

            @Override
            public void onClick(View v) {
                // on selecting grid view image
                // launch full screen activity
                Intent i = new Intent(_activity, FullScreenViewActivity.class);
                i.putExtra("position", _postion);
                _activity.startActivity(i);
            }

        }

        /*
         * Resizing image size
         */
        public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
            try {

                File f = new File(filePath);

                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);

                final int REQUIRED_WIDTH = WIDTH;
                final int REQUIRED_HIGHT = HIGHT;
                int scale = 1;
                while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
                        && o.outHeight / scale / 2 >= REQUIRED_HIGHT)
                    scale *= 2;

                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }

    }

我尝试了不同的方法,我在stackoverflow上找到了(其中一个我在上面实现了),但我仍然面临问题。 任何帮助都非常感谢。

我相信问题在这里

gridView.setAdapter(new GridViewImageAdapter(getActivity()));

1 个答案:

答案 0 :(得分:3)

您定义的构造函数采用参数:

public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,int imageWidth)

并尝试使用一个不正确的参数初始化适配器对象。

getActivity()在片段中工作,但构造函数中有一个参数(上下文)在GridViewImageAdapter中找不到。

所以改变:

gridView.setAdapter(new GridViewImageAdapter(getActivity()));

到:

gridView.setAdapter(new GridViewImageAdapter(getActivity() , imagePaths , columnWidth  ));

但您需要先初始化您的值,