如何使用GridView变量从onCreateView类到片段中的另一个类?

时间:2018-10-23 08:04:28

标签: android variables android-fragments gridview

我有一个片段,并且在onCreateView内初始化了一个GridView变量: mgridView ,但是由于出现错误,我无法在另一个类中使用它- 无法解析变量mgridView 。我在代码中使用mContext变量遇到了类似的问题,但是通过在onCreateView内执行 private Context mContext = null; mContext mContext = this.getActivity(); *来解决此问题idk如何处理mgridView。

代码-

public class DubsFragment extends Fragment {
    private static final String TAG = "Dubs Fragment";
    private Context mContext = null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mydubs, container, false);

        GridView mgridView = view.findViewById(R.id.gridView);
        mContext = this.getActivity();
        tempGridsetup();

        return view;

    }

        private void tempGridsetup() {

        ArrayList<String> imgURLs = new ArrayList<>();

            imgURLs.add("https://jerrybanfield.com/wp-content/uploads/2017/04/ufo-title.jpg");
            imgURLs.add("https://i.ytimg.com/vi/fb7T1v_VHpE/maxresdefault.jpg");
            imgURLs.add("https://cbsnews3.cbsistatic.com/hub/i/r/2010/11/10/a5cb16e6-a642-11e2-a3f0-029118418759/thumbnail/1200x630/f599cb2f266baaae27ae8b608b45e70d/UFO.jpg");

            setupImageGrid(imgURLs);

        }


        private void setupImageGrid(ArrayList<String> imgURLs){

            GridImageAdapter adapter = new GridImageAdapter(mContext, R.layout.layout_grid_imageview, "", imgURLs);
            mgridView.setAdapter(adapter);
    }

    }

可能是一个基本问题,但是我在stackoverflow中搜索了类似的问题,但没有找到解决我问题的线索。

1 个答案:

答案 0 :(得分:1)

使用onCreate定义网格视图。

 private static final String TAG = "Dubs Fragment";
        private Context mContext = null;
        public  GridView mgridView;

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_mydubs, container, false);

            mgridView = view.findViewById(R.id.gridView);
            mContext = this.getActivity();
            tempGridsetup();

            return view;

        }