[英]RecyclerView Items Duplicating when navigating through different Fragments, arraylist.clear() doesn´t work
这是我在此的头一篇博文。 我在片段中使用 RecyclerView 时遇到问题。 对于 BottomNavigationMenu,我有两个不同的片段,每次我回到 RecyclerView 所在的片段时,项目都会重复。我尝试使用 arraylist.clear(); 正如这里多次建议的那样,但它不起作用。 在使用带有片段而不是 BottomNavigationMenu 的 TabLayout 之前,我使用了完全相同的代码,并且效果很好。 这些项目根本没有重复..,我正在为音频流应用程序制作音乐库,并且我正在使用实时 firebase 将 RecyclerView 的信息打印到屏幕上:如果我使用; if (audioFileArrayList == null) { loadData(). 它解决了这个问题,因为这样它不会打印两次信息,但我认为这不是解决这个问题的正确方法。 似乎每次我 go 回到 RecyclerView 片段时,视图都不会刷新,而是在底部一次又一次地打印所有内容......
这是主活动:
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
getSupportActionBar().hide(); //escondemos la action bar
bottomNavigationView = binding.bottomNavigationID;
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_id, new BibliotecaFragment()).commit();
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragmentSeleccionado = null;
switch (item.getItemId()) {
case R.id.biblioteca_ID:
fragmentSeleccionado = new BibliotecaFragment();
break;
case R.id.playlists_ID:
fragmentSeleccionado = new PlayListsFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_id, fragmentSeleccionado).commit();
return true;
}
});
}
}
这是图书馆的片段,正如我之前所说,如果我使用
if (audioFileArrayList == null) {
loadData();
}
它阻止它打印两次。
公共 class BibliotecaFragment 扩展片段 {
FragmentBibliotecaBinding binding;
RecyclerView recyclerView;
AudioFileAdapter audioFileAdapter;
static ArrayList<AudioFile> audioFileArrayList;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentBibliotecaBinding.inflate(getLayoutInflater());
recyclerView = binding.BibliotecaFragmentRecyclerViewID;
recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
audioFileAdapter = new AudioFileAdapter(getContext());
recyclerView.setAdapter(audioFileAdapter);
loadData();
return binding.getRoot();
}
public void loadData() {
DatabaseReference dbr = FirebaseDatabase.getInstance().getReference();
dbr.child("biblioteca").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
audioFileArrayList = new ArrayList<>();
for (DataSnapshot data : snapshot.getChildren()) {
AudioFile audioFile = data.getValue(AudioFile.class);
audioFileArrayList.add(audioFile);
}
audioFileAdapter.setItems(audioFileArrayList);
audioFileAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
这是我的适配器:
public class AudioFileAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
static ArrayList<AudioFile> audioFileList = new ArrayList<>();
public AudioFileAdapter(Context ctx) {
this.context = ctx;
}
public void setItems(ArrayList<AudioFile> audioFile) {
audioFileList.addAll(audioFile);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.audio_item, parent, false);
return new AudioFileViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
AudioFileViewHolder audioFileViewHolder = (AudioFileViewHolder) holder;
AudioFile audioFile = audioFileList.get(position);
audioFileViewHolder.txtArtist.setText(audioFile.getArtist());
audioFileViewHolder.txtTitle.setText(audioFile.getTitle());
Glide.with(context).load(audioFile.getImgURL()).into(audioFileViewHolder.imageViewPicture);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putInt("posicion", position);
Intent intent = new Intent(context, Reproductor.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
});
((AudioFileViewHolder) holder).imageViewMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PopupMenu popupMenu = new PopupMenu(context, view);
popupMenu.getMenuInflater().inflate(R.menu.audio_item_popup_menu, popupMenu.getMenu());
popupMenu.show();
popupMenu.setOnMenuItemClickListener((menuItem) -> {
switch (menuItem.getItemId()) {
case R.id.agregar_a_lista_ID: {
break;
}
case R.id.eliminar_de_biblioteca_ID: {
eliminar(position);
break;
}
}
return true;
});
}
});
}
public void eliminar(int position) {
String id = audioFileList.get(position).getId();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query delete = databaseReference.child("biblioteca").orderByChild("id").equalTo(id);
delete.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
audioFileList.clear(); // importante limpiar la lista cada vez que se elimina un item para que no se dupliquen en la parte de abajo...
for (DataSnapshot data : dataSnapshot.getChildren()) {
data.getRef().removeValue();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public int getItemCount() {
return audioFileList.size();
}
public interface ItemClickListener { //interfaz listener para RyclerView
void onItemClick(AudioFile audioFile);
}
}
我的视图持有者:
public class AudioFileViewHolder extends RecyclerView.ViewHolder {
public TextView txtArtist, txtTitle;
public ImageView imageViewPicture, imageViewMenu;
public AudioFileViewHolder(@NonNull View itemView) {
super(itemView);
txtArtist = itemView.findViewById(R.id.artistID);
txtTitle = itemView.findViewById(R.id.titleID);
imageViewPicture = itemView.findViewById(R.id.item_imageID);
imageViewMenu = itemView.findViewById(R.id.item_menu_ID);
}
}
MainActivity 的 XML 代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/frame_layout_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottom_navigation_ID" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation_ID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
app:menu="@menu/bottom_navigation_menu" />
</RelativeLayout>
RecyclerView 的 XML 代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BibliotecaFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/BibliotecaFragmentRecyclerViewID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3C3A3A"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
并将每个项目的 XML 代码放入 RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/audio_itemID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="@color/black"
android:orientation="horizontal">
<ImageView
android:id="@+id/item_imageID"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@drawable/ic_launcher_foreground"
android:padding="5dp" />
<TextView
android:id="@+id/artistID"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center"
android:text="Artist"
android:textColor="@color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center"
android:text="-"
android:textColor="@color/white" />
<TextView
android:id="@+id/titleID"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center"
android:text="Title"
android:textColor="@color/white" />
<ImageView
android:id="@+id/item_menu_ID"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="150dp"
android:background="@drawable/ic_baseline_more_vert"
android:padding="5dp"
android:layout_gravity="center_vertical"/>
</LinearLayout>
对不起我的英语,我知道它并不完美,我希望你们能帮助我。
鲁本。
我有同样的问题,目前没有答案。 你可以试试我的方法,但只有在你的回收站物品确定的情况下才有效。 转到您的查看器类=>
@Override
public int getItemCount() {
return num;
}
其中 num 是您在 recyclerview 中的项目数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.