如何在另一个片段内膨胀另一个布局

Posted

技术标签:

【中文标题】如何在另一个片段内膨胀另一个布局【英文标题】:How to inflate another layout inside of another fragment 【发布时间】:2021-06-26 22:29:03 【问题描述】:

您好,我试图在我的应用程序中为 home_items.xml 充气,但它不起作用,它只给了我 fragment_home.xml 只是我想知道如何解决这个问题? (我可以发送我的代码的任何部分。)

HomeAdapter.java:

package com.example.soulforge.adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.soulforge.R;
import com.example.soulforge.model.HomeModel;

import java.util.List;
import java.util.Random;

import de.hdodenhof.circleimageview.CircleImageView;


public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeHolder>

    private List<HomeModel> list;
    Context context;

    public HomeAdapter(List<HomeModel> list, Context context) 
        this.list = list;
        this.context = context;
    

    @NonNull
    @Override
    public HomeHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_items,  parent, false);
        return new HomeHolder(view);
    

    @Override
    public void onBindViewHolder(@NonNull HomeHolder holder, int position) 

        holder.userNameTv.setText(list.get(position).getUserName());
        holder.timeTv.setText(""+list.get(position).getTimestamp());


        int count = list.get(position).getLikeCount();
        if(count ==0)
            holder.likeCountTv.setVisibility(View.INVISIBLE);
        else if (count == 1)
            holder.likeCountTv.setText(count + " like");
        else
            holder.likeCountTv.setText(count + " likes");
        

        holder.descriptionTv.setText(list.get(position).getDescription());


        Random random = new Random();

        int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));

        Glide.with(context.getApplicationContext())
                .load(list.get(position).getProfileImage())
                .placeholder(R.drawable.ic_person)
                .timeout(6500)
                .into(holder.profileImage);

        Glide.with(context.getApplicationContext())
                .load(list.get(position).getImageUrl())
                .placeholder(new ColorDrawable(color))
                .timeout(7000)
                .into(holder.imageView);

    

    @Override
    public int getItemCount() 

        return list.size();
    

    static class HomeHolder extends RecyclerView.ViewHolder
        private CircleImageView profileImage;
        private TextView userNameTv, timeTv, likeCountTv, descriptionTv;
        private ImageView imageView;
        private ImageButton likeBtn, commentBtn, shareBtn;

        public HomeHolder(@NonNull View itemView) 
            super(itemView);

            profileImage = itemView.findViewById(R.id.profileImage);
            imageView = itemView.findViewById(R.id.imageView);
            userNameTv = itemView.findViewById(R.id.nameTv);
            timeTv = itemView.findViewById(R.id.timeTv);
            likeCountTv = itemView.findViewById(R.id.likeCountTv);
            likeBtn = itemView.findViewById(R.id.likeBtn);
            commentBtn = itemView.findViewById(R.id.commentBtn);
            shareBtn = itemView.findViewById(R.id.shareBtn);
            descriptionTv = itemView.findViewById(R.id.descTv);


        
    

Home.java:

package com.example.soulforge.fragments;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.soulforge.R;
import com.example.soulforge.adapter.HomeAdapter;
import com.example.soulforge.model.HomeModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

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


public class Home extends Fragment 

    private RecyclerView recyclerView;


    HomeAdapter adapter;

    private List<HomeModel> list;

    private FirebaseUser user;

    public Home() 
        // Required empty public constructor
    


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        return inflater.inflate(R.layout.fragment_home, container, false);
    

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) 
        super.onViewCreated(view, savedInstanceState);

        init(view);

        list = new ArrayList<>();
        adapter = new HomeAdapter(list, getContext());
        recyclerView.setAdapter(adapter);

        loadDataFromFirestore();
    

    private void init(View view) 

        Toolbar toolbar = view.findViewById(R.id.toolbar);
        if (getActivity() != null)
            ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        FirebaseAuth auth = FirebaseAuth.getInstance();
        user = auth.getCurrentUser();
    

    public void loadDataFromFirestore() 
        CollectionReference reference = FirebaseFirestore.getInstance().collection("Users")
                .document(user.getUid())
                .collection("Post Images");

        reference.addSnapshotListener(new EventListener<QuerySnapshot>() 
            @Override
            public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) 
                if (error != null) 
                    Log.e("Error: ", error.getMessage());
                    return;
                
                if (value == null)
                    return;
                for (QueryDocumentSnapshot snapshot : value) 
                    if (!snapshot.exists())
                        return;

                    HomeModel model = snapshot.toObject(HomeModel.class);
                    list.add(new HomeModel(
                            model.getUserName(),
                            model.getProfileImage(),
                            model.getImageUrl(),
                            model.getUid(),
                            model.getComments(),
                            model.getDescription(),
                            model.getId(),
                            model.getTimestamp(),
                            model.getLikeCount()
                    ));
                
                adapter.notifyDataSetChanged();
            
        );

    

知道如何解决这个问题吗?我尝试使用 inflate 但它无法工作,因为它缺少家庭项目 xml enter image description here。

在你说我已经清除和重建以及解决此问题的所有常见问题解答之前

【问题讨论】:

【参考方案1】:

您正在更新错误的列表实例

在适配器内部创建一个方法

public updateList(List<HomeModel> list) 
    this.list = list;
    notifyDataSetChanged()

然后这样称呼它:

    reference.addSnapshotListener(new EventListener<QuerySnapshot>() 
        @Override
        public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) 
                ... 
                adapter.updateList(new HomeModel(
                        model.getUserName(),
                        model.getProfileImage(),
                        model.getImageUrl(),
                        model.getUid(),
                        model.getComments(),
                        model.getDescription(),
                        model.getId(),
                        model.getTimestamp(),
                        model.getLikeCount()
                ));
            
        
    );

【讨论】:

以上是关于如何在另一个片段内膨胀另一个布局的主要内容,如果未能解决你的问题,请参考以下文章

在片段中,如何查找活动布局中定义的视图?

Android:在片段内膨胀自定义视图

如何在另一个片段中访问和使用一个片段的按钮?

如何在另一个片段中使用 YouTubePlayerFragment 加载 YouTubePlayer? (安卓)

如何在另一个 Fragment 中更新 ListView?

如何将捆绑从一个活动传递到放置在另一个活动中的片段?