当前位置: 首页 > 知识库问答 >
问题:

如何使用recycleradapter和firebase获取位置并显示详细活动数据

巫马望
2023-03-14

我有一个listview,显示来自firebase.Thelistview作品的数据prefectly.But现在我想在我的回收器适配器中实现一个onClick侦听器,然后在新活动中显示更多详细信息。我到处寻找解决方案,但找不到。我知道我应该使用Firebase UI。

这是使用回收器adaper将数据从firebase显示到listview的片段:

 public class CategoryFragment extends Fragment {
    private static final String TAG = "CategoryFragment";


    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    // private Adapter adapter;
    private List<ListItem> listItems;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;

    private AdapterView.OnItemSelectedListener listener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
 View rootView =inflater.inflate(R.layout.recycler_view,container,false);
        listItems = new ArrayList<>();
         adapter = new CategoryRecycler(listItems,getContext());
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        getFirebaseData();
        progressBar = rootView.findViewById(R.id.progressBar);
        recyclerView = rootView.findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        int tilePadding = getResources().getDimensionPixelSize(R.dimen.tile_padding);
        recyclerView.setPadding(tilePadding, tilePadding, tilePadding, tilePadding);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        return recyclerView;

        //return rootView

    }

    private void getFirebaseData() {

        myRef = mFirebaseDatabase.getReference("Users");
        myRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                ListItem data = dataSnapshot.getValue(ListItem.class);
                listItems.add(data);
                recyclerView.setAdapter(adapter);


            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {


            }
        });
    }
}

下面是我在回收器适配器中实现onclick的尝试:

public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
    super(inflater.inflate(R.layout.category_item_tile, parent, false));
    username = itemView.findViewById(R.id.list_title);
    imageUrl = itemView.findViewById(R.id.list_avatar);
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Context context = v.getContext();
          Intent pDetail = new Intent(context, ProfileDetail.class);
            pDetail.putExtra(ProfileDetail.EXTRA_POSITION, getAdapterPosition());
           context.startActivity(pDetail);
        }
    });
}

这是我的详细活动:

public class ProfileDetail extends AppCompatActivity {
    private static final String TAG = "EXTRA_POSITION";
    public static final String EXTRA_POSITION = "profile_detail";
    private List<ListItem> listItems;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
    private TextView tvName, tvSummary, tvStatus, tvDetail;
    private ImageView ivImage;
    private ImageView ivImageCard;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.categorydetails);
        listItems = new ArrayList<>();
        ivImage = findViewById(R.id.userAvatar);
        ivImageCard = findViewById(R.id.header_img);
        tvName = findViewById(R.id.userProfileName);
        tvSummary = findViewById(R.id.ProfileSummary);
        tvStatus = findViewById(R.id.userStatus);
        tvDetail = findViewById(R.id.ProfileDetail);

    }

}

这是适配器的完整代码:

    public class CategoryRecycler extends RecyclerView.Adapter<CategoryRecycler.ViewHolder> {
    private List<ListItem> listItems;
    private Context context;
    public CategoryRecycler(List<ListItem>listItems,Context context) {
        this.listItems = listItems;
        this.context =context;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ListItem listItem = listItems.get(position);
        holder.username.setText(listItem.getUsername());
        //holder.summary.setText(listItem.getSummary());
        Picasso.with(context).load(listItem.getImageurl()).into(holder.imageUrl);
    }
    @Override
    public int getItemCount() {
        return listItems.size();
    }

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView username;
    public TextView summary;
    public ImageView imageUrl;


    public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.category_item_tile, parent, false));
        username = itemView.findViewById(R.id.list_title);
        imageUrl = itemView.findViewById(R.id.list_avatar);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Context context = v.getContext();
              Intent pDetail = new Intent(context, ProfileDetail.class);
                pDetail.putExtra(ProfileDetail.EXTRA_POSITION, getAdapterPosition());
               context.startActivity(pDetail);
            }
        });
    }
}


}

onBindViewHolder holder呼叫:

holder.username.setText(listItem.getUsername());
Picasso.with(context).load(listItem.getImageurl()).into(holder.imageUrl);

我的毕加索形象管理需要上下文。

//声明上下文

private Context context;

//使用上下文

this.context =context;

但是如果你知道任何其他不使用图像上下文的方法,我会感谢你的建议。

共有1个答案

澹台成龙
2023-03-14

在您的适配器中实现onClick动作的最佳方式是在您的适配器中创建一个接口,并通过使它实现这样的接口将其链接到您的片段,然后在片段中启动新的活动。我已经这样重构了您的适配器:

public class SpecialAdapter extends RecyclerView.Adapter<SpecialAdapter.SpecialViewHolder> {

    List<ListItem> items;
    OnItemClickListener callback;

    public SpecialAdapter(List<ListItem> items, OnItemClickListener callback) {
        this.items = items;
        this.callback = callback;
    }

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

    @Override
    public void onBindViewHolder(@NonNull SpecialViewHolder holder, int position) {
        ListItem listItem = items.get(position);
        holder.username.setText(listItem.getUsername());
        holder.imageUrl.setVisibility(View.VISIBLE);
    }

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

    class SpecialViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView username;
        public ImageView imageUrl;

        public SpecialViewHolder(View itemView) {
            super(itemView);

            username = itemView.findViewById(R.id.list_title);
            imageUrl = itemView.findViewById(R.id.list_avatar);

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            callback.onItemClick(getAdapterPosition());
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int pos);
    }
}

我重构了你的片段:

public class CategoryFragment extends Fragment implements SpecialAdapter.OnItemClickListener {
    private static final String TAG = "CategoryFragment";


    private RecyclerView recyclerView;
    private SpecialAdapter adapter;
    // private Adapter adapter;
    private List<ListItem> listItems;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;

    private AdapterView.OnItemSelectedListener listener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView =inflater.inflate(R.layout.recycler_view,container,false);
        listItems = new ArrayList<>();
        adapter = new SpecialAdapter(listItems, this);
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        getFirebaseData();
        progressBar = rootView.findViewById(R.id.progressBar);
        recyclerView = rootView.findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        int tilePadding = getResources().getDimensionPixelSize(R.dimen.tile_padding);
        recyclerView.setPadding(tilePadding, tilePadding, tilePadding, tilePadding);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        recyclerView.setAdapter(adapter);
        return recyclerView;

        //return rootView

    }

    private void getFirebaseData() {

        myRef = mFirebaseDatabase.getReference("Users");
        myRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                ListItem data = dataSnapshot.getValue(ListItem.class);
                listItems.add(data);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {


            }
        });
    }

    @Override
    public void onItemClick(int pos) {

        Intent pDetail = new Intent(this.getContext(), ProfileDetail.class);

        ListItem item = listItems.get(pos);
        pDetail.putExtra(ProfileDetail.EXTRA_POSITION, item.getUserid());
        startActivity(pDetail);
    }
}

我想你的ListItem看起来像这样:

public class ListItem {

    private String details;
    private String imageurl;
    private String status;
    private String summary;
    private String userid;
    private String username;

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public String getImageurl() {
        return imageurl;
    }

    public void setImageurl(String imageurl) {
        this.imageurl = imageurl;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

最后,在您的详细信息活动中,您可以简单地获取此id并读取数据库:

public class ProfileDetail extends AppCompatActivity {
    private static final String TAG = "EXTRA_POSITION";
    public static final String EXTRA_POSITION = "profile_detail";
    private List<ListItem> listItems;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
    private TextView tvName, tvSummary, tvStatus, tvDetail;
    private ImageView ivImage;
    private ImageView ivImageCard;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.categorydetails);
        listItems = new ArrayList<>();
        ivImage = findViewById(R.id.userAvatar);
        ivImageCard = findViewById(R.id.header_img);
        tvName = findViewById(R.id.userProfileName);
        tvSummary = findViewById(R.id.ProfileSummary);
        tvStatus = findViewById(R.id.userStatus);
        tvDetail = findViewById(R.id.ProfileDetail);

        String userid = getIntent().getExtras().getString(ProfileDetail.EXTRA_POSITION);
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference("Users");
        myRef.child(userid).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                ListItem item = (ListItem) dataSnapshot.getValue(ListItem.class);
                if(item!=null){
                   tvName.setText(item.getUsername());
                }

            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });


    }

}

如果您不想在详细信息活动中发出请求,您可以使ListItem(parcelable)可序列化,并将其直接作为额外的意图。请参阅此处。使用Serializable通过意图传递数据

 类似资料:
  • 我有以下JSON数据: 我想在标记中显示它。我试着这样做:

  • 在MainActivity中,我有一个CardView项目的RecyclerView列表。 单击任何CardView都会启动DetailsActivity CardView,它显示数据库中该特定CardView的更多数据。 单击DetailsActivity CardView会启动EditActivity来编辑该CardView的数据。单击“保存”按钮将用户返回到DetailsActivity,这

  • 问题内容: 我正在尝试使用JavaScript检测浏览器滚动条的位置,以确定当前视图在页面中的位置。我的猜测是,我必须检测轨道上的拇指在哪里,然后检测拇指的高度占轨道总高度的百分比。我是不是过于复杂了,还是JavaScript提供了比这更简单的解决方案?任何想法代码明智? 问题答案: 您可以使用和获取分别滚动的垂直和水平偏移。可如果你关心整个页面。如果需要百分比,可以将其与和(再次可能是主体)进行

  • 本文向大家介绍如何使用HTML5地理位置和Google Maps显示当前位置?,包括了如何使用HTML5地理位置和Google Maps显示当前位置?的使用技巧和注意事项,需要的朋友参考一下 HTML5 Geolocation API使您可以与自己喜欢的网站共享位置。Javascript可以捕获您的纬度和经度,并且可以发送到后端Web服务器,并可以进行精美的位置感知操作,例如查找本地商家或在映射上

  • 我开发了一个聊天应用程序。我试图从firebase数据库中获取数据,并将其显示在一个recyclerview中,但这并不起作用。我在谷歌上搜索了它,我试了很多选项,但它什么都显示不出来。我做错了什么?这些活动是: 1.主活动(我想在哪里显示数据) }

  • 问题内容: 我使用reactjs并想处理带事件的滚动。 首先,我使用绘制了帖子列表。 其次,通过按列表中的每个帖子,它将显示帖子详细信息并滚动到顶部(因为我将帖子详细信息置于页面的顶部位置)。 第三,通过单击帖子详细信息,它将返回以前的帖子列表,但是我希望网站将滚动到要单击的帖子的位置。 我这样使用: 单击事件以查看帖子详细信息: 我想获取的状态,然后可以按滚动到所点击帖子的位置。 问题答案: 这