[英]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.