片段中的Android Studio RecyclerView [重复]

Posted

技术标签:

【中文标题】片段中的Android Studio RecyclerView [重复]【英文标题】:Android Studio RecyclerView in Fragments [duplicate] 【发布时间】:2018-07-24 04:31:17 【问题描述】:

我有这段代码,它在Fragment 中集成了一个RecyclerView,但是这一行:

RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager (this, 3);

给我一​​个错误,它告诉我:

GridLayoutManager中的GridLayoutManager(android.content.Context,int)不能应用到(com.example.julianrc1.petracecitm.PerdidosGaleria_Fragment,int)

我不知道为什么,有什么想法吗?

这是我正在使用的代码:

package com.example.julianrc1.petracecitm;

import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class PerdidosGaleria_Fragment extends Fragment 

    private RecyclerView recyclerView;
    private AnunciosAdapter adapter;
    private List<Anuncio> anuncioList;

    public PerdidosGaleria_Fragment() 
        // 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_perdidosgaleria, container, false);
        Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

        //initCollapsingToolbar();

        recyclerView = (RecyclerView)  rootView.findViewById(R.id.content_main);

        anuncioList = new ArrayList<>();
        adapter = new AnunciosAdapter(this, anuncioList);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 3);//columnas que quieres por filas
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        prepareAlbums();

        try 
          //  Glide.with(this).load(R.drawable.cover).into((ImageView) rootView.findViewById(R.id.backdrop));
         catch (Exception e) 
            e.printStackTrace();
        


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_perdidosgaleria, container, false);
    
/*
    private void initCollapsingToolbar() 

        final CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle(" ");
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
        appBarLayout.setExpanded(true);

        // hiding & showing the title when toolbar expanded & collapsed
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() 
            boolean isShow = false;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) 
                if (scrollRange == -1) 
                    scrollRange = appBarLayout.getTotalScrollRange();
                
                if (scrollRange + verticalOffset == 0) 
                    collapsingToolbar.setTitle(getString(R.string.app_name));
                    isShow = true;
                 else if (isShow) 
                    collapsingToolbar.setTitle(" ");
                    isShow = false;
                
            
        );
    
*/
    /**
     * Adding few albums for testing
     */
    private void prepareAlbums() 
        int[] covers = new int[]
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon;

        Anuncio a = new Anuncio("True Romance", 13, covers[0]);
        anuncioList.add(a);

        a = new  Anuncio("Xscpae", 8, covers[1]);
        anuncioList.add(a);

        a = new  Anuncio("Maroon 5", 11, covers[2]);
        anuncioList.add(a);

        a = new  Anuncio("Born to Die", 12, covers[3]);
        anuncioList.add(a);

        a = new  Anuncio("Honeymoon", 14, covers[4]);
        anuncioList.add(a);

        a = new  Anuncio("I Need a Doctor", 1, covers[5]);
        anuncioList.add(a);

        a = new  Anuncio("Loud", 11, covers[6]);
        anuncioList.add(a);

        a = new  Anuncio("Legend", 14, covers[7]);
        anuncioList.add(a);

        a = new  Anuncio("Hello", 11, covers[8]);
        anuncioList.add(a);

        a = new  Anuncio("Greatest Hits", 17, covers[9]);
        anuncioList.add(a);

        adapter.notifyDataSetChanged();
    

    /**
     * RecyclerView item decoration - give equal margin around grid item
     */
    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
                
            
        
    

    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) 
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    

【问题讨论】:

将 new GridLayoutManager(this, 3) 中的 'this' 替换为 getActivity() 【参考方案1】:

this 更改为 getActivity() ,因为您在 Fragment 中使用了 recyclerView

thisActivity 的上下文。 getActivity()Fragment 的上下文。

代码:

  RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 3); 

 RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3); 

【讨论】:

【参考方案2】:

请在new GridLayoutManager(getActivity(), 3) 中使用getActivity() 而不是new GridLayoutManager(this, 3)

原因:GridLayoutManager(Context context, int spanCount) 在第一个参数中需要一个 Context 类型的实例,第二个参数需要一个跨度计数。

当你使用this 时,你传递的是一个 Fragment 实例,这不是传递的正确参数。

乐于助人。

【讨论】:

【参考方案3】:

Fragment类不扩展Context类的主要原因

java.lang.Object
   ↳    android.app.Fragment

并且Activity 类有一个上下文

java.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.view.ContextThemeWrapper
               ↳    android.app.Activity

这就是为什么当你使用this 时它会在活动中起作用而在片段中不起作用

那么你需要在片段中使用getActivity() 而不是this 来传递上下文

【讨论】:

【参考方案4】:

您必须更改以下内容:- 您不能使用片段代替上下文,因为片段不扩展上下文。但是 Activity 扩展了上下文。

您可以使用 getActivity(),它返回与片段关联的活动。 Activity 是一个上下文(因为 Activity 扩展了 Context)。

  RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 3);

 RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);

【讨论】:

【参考方案5】:

改变

new GridLayoutManager(this, 3)

到:

new GridLayoutManager(getActivity(), 3)

【讨论】:

以上是关于片段中的Android Studio RecyclerView [重复]的主要内容,如果未能解决你的问题,请参考以下文章

片段中的TextView在Android Studio中返回Null

从 Android Studio 中的片段将数据写入 Firebase

片段中的意图不断与清单崩溃问题,android studio

通过按下 Android Studio 中的片段中的按钮进入新页面

播放android studio时片段中的VideoView没有声音

Android Studio - 片段按钮操作