【问题标题】:Fragment getActivity not working片段 getActivity 不起作用
【发布时间】:2016-12-20 11:32:46
【问题描述】:

我正在关注this 教程,并尝试为每个用户而不是相册创建个人资料页面。但是,我使用的是片段而不是活动,并意识到我的代码与本教程有所不同。

我已经使用 Android 开发者文档和我自己的知识修复了从活动转移到片段的大多数错误,但是我似乎找不到解决这个问题的方法,感谢任何帮助。

我有以下代码可以正常工作:

recyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);

但是当我尝试添加到回收站视图时,我得到一个错误:

recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));

无法解析符号 GridSpacingItemDecoration

无法解析方法 dpToPx(int)

这是所要求的类

 public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }
}

【问题讨论】:

  • 复制GridSpacingItemDecorationdpToPx()到你的片段。
  • 不用担心我解决了这个问题,这是由于我创建了另一个类
  • 那么,您的问题现在解决了吗? @UCLCoder

标签: java android android-activity fragment android-context


【解决方案1】:

将此方法设为私有

【讨论】:

  • 请求详细信息,请将其放在评论中,而不是回答!不是一个好习惯!
  • @UCLCoder,如果我的建议也有效,请接受答案,以便其他人获得帮助
猜你喜欢
  • 2015-10-21
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
相关资源
最近更新 更多