【问题标题】:recycler view is not shown in fragment回收站视图未显示在片段中
【发布时间】:2022-01-11 02:50:31
【问题描述】:

出于某种原因,我将我的活动更改为片段,但现在我的回收器视图未显示我还检查了我想在回收器视图上显示的 ArrayList,它不为空。相同的代码在另一个活动和片段中工作,但不在此片段中。请有人帮帮我!!提前谢谢你

我的片段代码

    public class HomeSkillsFragment extends Fragment {

    private EditText Search;
    private ImageView back;
    private RecyclerView recyclerView;
    private ArrayList<Post> postItem;
    private postAdapter adapter;
    private GridLayoutManager gridLayoutManager;
    private DatabaseReference reference;
    private BottomNavigationVisibility bottomNavigationVisibility;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home_skills, container, false);
    }


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

        bottomNavigationVisibility = new BottomNavigationVisibility(getActivity());
        bottomNavigationVisibility.hideBottomNavigation();

        //init Views
        Search = getActivity().findViewById(R.id.search_editText);
        back = getActivity().findViewById(R.id.back);
        recyclerView = getActivity().findViewById(R.id.recyclerView);
        gridLayoutManager = new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(gridLayoutManager);

        //getting Data from Database
        getDataFromDB();

        //click handle, back
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomNavigationVisibility.showBottomNavigation();
                NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
                navController.navigate(R.id.navigation_home);

            }
        });
    }


    private void getDataFromDB(){

        postItem = new ArrayList<>();
        //initialize database
        reference = FirebaseDatabase.getInstance().getReference("Posts");
        reference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        for(DataSnapshot dataSnapshot: snapshot.getChildren()){
                            Post post = dataSnapshot.getValue(Post.class);
                            if(post.getCategory().equals("Skills, M" ) || post.getCategory().equals("Skills, S"))
                                postItem.add(post);
                        }

                        adapter = new postAdapter(getContext(),postItem);
                        recyclerView.setAdapter(adapter);
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        Toast.makeText(getContext(),"Something went Wrong",Toast.LENGTH_SHORT).show();

                    }
                });

    }
}

我的适配器代码:

 public class postAdapter extends RecyclerView.Adapter<postAdapter.PostViewHolder> {

    LayoutInflater mInflater;
    private ArrayList<Post> mPost;
    Context context;

    public postAdapter(Context context, ArrayList<Post> posts) {
        mInflater = LayoutInflater.from(context);
        this.mPost = posts;
        this.context=context;
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.list_item,parent,false);
        return new PostViewHolder(itemView,this);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {

        //setting post title
        Post currentPost = mPost.get(position);
        holder.itemNameTextView.setText(currentPost.getPost_Title());

        //setting InExchange
        if(currentPost.getCategory().equals("Skills, M") || currentPost.getCategory().equals("Educational Accessories, M")){
            holder.inExchangeTextView.setText("Rs. " + currentPost.getIn_Exchange());
            holder.inExchangeTextView.setTextColor(context.getColor(R.color.blue));
            holder.exchangeIcon.setVisibility(View.VISIBLE);
        }
        else if(currentPost.getCategory().equals("Skills, S") || currentPost.getCategory().equals("Educational Accessories, A")){
            holder.inExchangeTextView.setText(currentPost.getIn_Exchange());
            holder.inExchangeTextView.setTextColor(context.getColor(R.color.blue));
            holder.exchangeIcon.setVisibility(View.VISIBLE);
        }
        else{
            holder.inExchangeTextView.setText(currentPost.getIn_Exchange());
            holder.inExchangeTextView.setTextColor(context.getColor(R.color.green));
            holder.exchangeIcon.setVisibility(View.INVISIBLE);
        }

        //setting image
        Picasso.get().load(currentPost.getImage_Url_1()).into(holder.image);
        holder.image.setClipToOutline(true);

        //setting institution name
        FirebaseDatabase.getInstance().getReference("Users/"+currentPost.getUid()+"/").getRef().addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    holder.institutionName.setText(snapshot.child("institution").getValue(String.class));
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(context,"Something went wrong",Toast.LENGTH_SHORT).show();

            }
        });

        //handle click of item
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("currentPost", currentPost);
                Navigation.findNavController(view).navigate(R.id.action_navigation_home_to_homeDetailFragment, bundle);
            }
        });

    }

    @Override
    public int getItemCount() {
        return mPost.size();
    }

    class PostViewHolder extends  RecyclerView.ViewHolder{

        TextView itemNameTextView;
        TextView inExchangeTextView ;
        TextView institutionName;
        ImageView image, exchangeIcon ;
        RecyclerView.Adapter mAdapter;

        public PostViewHolder(@NonNull View itemView, postAdapter adapter) {
            super(itemView);
            itemNameTextView = itemView.findViewById(R.id.itemName_TextView);
            inExchangeTextView = itemView.findViewById(R.id.inExchange_TextView);
            image = itemView.findViewById(R.id.imageView);
            institutionName = itemView.findViewById(R.id.institutionName);
            exchangeIcon = itemView.findViewById(R.id.exchange_icon);
            mAdapter = adapter;
        }
    }


}

我的 XML :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.home.HomeSkillsFragment">


    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayoutTop"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_130sdp"
        android:background="@drawable/top_background_rounded"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/_10sdp"
            android:layout_marginStart="@dimen/_12sdp"
            android:foreground="?android:attr/selectableItemBackgroundBorderless"
            android:src="@drawable/arrow_back"
            android:padding="@dimen/_8sdp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <EditText
            android:id="@+id/search_editText"
            style="@style/searchView"
            android:layout_width="0dp"
            android:layout_height="@dimen/_35sdp"
            android:layout_marginStart="@dimen/_10sdp"
            android:layout_marginTop="@dimen/_8sdp"
            android:inputType="text"
            android:includeFontPadding="false"
            android:singleLine="true"
            android:layout_marginEnd="@dimen/_16sdp"
            android:layout_marginBottom="@dimen/main_start_end_margin"
            android:hint="Search"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/back"
            app:layout_constraintTop_toTopOf="parent" />



    <ImageView
        android:id="@+id/skills_imageView"
        android:layout_width="@dimen/_50sdp"
        android:layout_height="@dimen/_50sdp"
        android:background="@drawable/searchview_bg"
        android:src="@drawable/ic_skills"
        android:scaleType="centerInside"
        android:layout_marginTop="@dimen/_8sdp"
        app:layout_constraintTop_toBottomOf="@id/search_editText"
        app:layout_constraintEnd_toEndOf="@+id/constraintLayoutTop"
        app:layout_constraintStart_toStartOf="@+id/constraintLayoutTop" />
<TextView
    android:id="@+id/skills_TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/_4sdp"
    android:fontFamily="@font/poppins_regular"
    android:text="Skills"
    android:textColor="@android:color/black"
    android:textSize="@dimen/_12ssp"
    android:includeFontPadding="false"
    app:layout_constraintTop_toBottomOf="@id/skills_imageView"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>


<TextView
    android:id="@+id/inExchange_TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="In Exchange"
    android:textSize="@dimen/_10ssp"
    android:textColor="@color/black"
    android:fontFamily="@font/poppins_medium"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/constraintLayoutTop"
    android:layout_marginTop="@dimen/_8sdp" />

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/_20sdp"
    app:layout_constraintTop_toBottomOf="@id/inExchange_TextView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    android:orientation="horizontal">

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="See All"
        android:scaleX="0.9"
        android:scaleY="0.9"
        android:textStyle="bold"
        style="@style/radioButton"
        android:fontFamily="@font/poppins_medium"
        android:includeFontPadding="false"
        android:id="@+id/radioButtonAll"
        android:checked="true"
        android:textSize="@dimen/_10sdp" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Give Money"
        style="@style/radioButton"
        android:scaleX="0.9"
        android:scaleY="0.9"
        android:textStyle="bold"
        android:includeFontPadding="false"
        android:fontFamily="@font/poppins_medium"
        android:id="@+id/radioButtonMoney"
        android:checked="false"
        android:textSize="@dimen/_10sdp" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:includeFontPadding="false"
        android:scaleX="0.9"
        android:scaleY="0.9"
        android:text="Teach Other Skill"
        style="@style/radioButton"
        android:textStyle="bold"
        android:fontFamily="@font/poppins_medium"
        android:id="@+id/radioButtonSkill"
        android:checked="false"
        android:textSize="@dimen/_10sdp" />
</RadioGroup>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginTop="@dimen/_10sdp"
    android:paddingLeft="@dimen/_12sdp"
    android:paddingRight="@dimen/_12sdp"
    android:paddingTop="@dimen/_8sdp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/radioGroup"
    app:layout_constraintVertical_weight="1" />

</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

    标签: java android android-fragments android-recyclerview android-adapter


    【解决方案1】:

    在您的代码中,您将尝试从活动中获取视图,而不是从片段中获取视图。

        Search = getActivity().findViewById(R.id.search_editText);
        back = getActivity().findViewById(R.id.back);
        recyclerView = getActivity().findViewById(R.id.recyclerView);
    

    使用 onViewCreated

    而不是 onActivityCreated

    更新了 HomeSkillFragment.class。

    public class HomeSkillsFragment extends Fragment {
    
        private EditText Search;
        private ImageView back;
        private RecyclerView recyclerView;
        private ArrayList<Post> postItem;
        private postAdapter adapter;
        private GridLayoutManager gridLayoutManager;
        private DatabaseReference reference;
        private BottomNavigationVisibility bottomNavigationVisibility;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_home_skills, container, false);
        }
    
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            
            bottomNavigationVisibility = new BottomNavigationVisibility(getActivity());
            bottomNavigationVisibility.hideBottomNavigation();
    
            //init Views
            Search = view.findViewById(R.id.search_editText);
            back = view.findViewById(R.id.back);
            recyclerView = view.findViewById(R.id.recyclerView);
            gridLayoutManager = new GridLayoutManager(getContext(), 2, GridLayoutManager.VERTICAL, false);
            recyclerView.setLayoutManager(gridLayoutManager);
    
            //getting Data from Database
            getDataFromDB();
    
            //click handle, back
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bottomNavigationVisibility.showBottomNavigation();
                    NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
                    navController.navigate(R.id.navigation_home);
    
                }
            });
        }
    
        private void getDataFromDB() {
    
            postItem = new ArrayList<>();
            //initialize database
            reference = FirebaseDatabase.getInstance().getReference("Posts");
            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                        Post post = dataSnapshot.getValue(Post.class);
                        if (post.getCategory().equals("Skills, M") || post.getCategory().equals("Skills, S"))
                            postItem.add(post);
                    }
    
                    adapter = new postAdapter(getContext(), postItem);
                    recyclerView.setAdapter(adapter);
                }
    
                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Toast.makeText(getContext(), "Something went Wrong", Toast.LENGTH_SHORT).show();
    
                }
            });
        }
    }
    

    【讨论】:

    • 等等,我马上更新答案
    • 告诉我一些信息,在这一行中 adapter = new postAdapter(getContext(), postItem); postItem 有数据吗?
    • 如果在recyclerView.setAdapter(adapter)之后添加;这个方法 adapter.notifyDataSetChanged() 你有同样的结果吗? BindViewHolder 上的内部适配器被调用?
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 2015-02-26
    • 2020-07-06
    相关资源
    最近更新 更多