我有一个只有RecycelerView
的活动。我想加载一个片段,当按下每个项目的RecycelerView
和一些数据应该发送到我的片段。在我的适配器,我写loadFragment
函数,并在onBindViewHolder
函数调用它。当我按下项目,显示片段,但我的RecycelrView
仍然存在和显示。在xml
文件MainActivity
我放了一个FrameLayout
与id flContent
,其中包括RecycelerView
.how隐藏RecycelerView
并将数据发送到我的片段?这是xml
的MainActivity
文件。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recPost"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
这是适配器的代码。
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.PostViewHolder> {
private Context context;
private ArrayList<Post> values;
public PostRecyclerAdapter(Context context, ArrayList<Post> values) {
this.context = context;
this.values = values;
}
@NonNull
@Override
public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyceler_post_item, parent, false);
return new PostViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final PostViewHolder holder, int position) {
final Post post=values.get(position);
holder.txtCaption.setText(post.getCaption());
holder.txtPreview.setText(post.getPreview());
holder.root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFragment(holder.layoutId,new InfoPostFragment());
}
});
}
private void loadFragment(int layoutId, Fragment fragment) {
FragmentManager manager =((FragmentActivity)context).getSupportFragmentManager();
manager.beginTransaction().replace(layoutId, fragment).commit();
}
public class PostViewHolder extends RecyclerView.ViewHolder{
private TextView txtCaption;
private TextView txtPreview;
private FrameLayout flContent;
private int layoutId;
private View root;
public PostViewHolder(View itemView) {
super(itemView);
root=itemView;
txtCaption=itemView.findViewById(R.id.txtCaption);
txtPreview=itemView.findViewById(R.id.txtPreview);
flContent=itemView.findViewById(R.id.flContent);
layoutId=R.id.flContent;
}
}
}
从FrameLayout中删除recyclerView
传递framelayout的引用或只使用loadFragment中的activity上下文来查找frameLayout和frameLayout.removeAllViews()
或者只是findViewById(R.android.recPost).setVisibility(View.GONE)
但有一点我想指出。管理Fragment生命周期应该是Activity文件的一部分,loadFragment代码不应该在Adapter类中。您可能想重新考虑这种方法。为它实现一个回调接口。