如何解决有没有办法检查Adapter类之外的RecyclerView类是否为空?
我正在构建这个简单的记事本应用程序。所有笔记都托管在RecyclerView中,并且有一个按钮可用于删除所有笔记。现在,当用户按下按钮删除所有笔记时,将弹出一个AlertDialog。事实是,即使应用程序中没有注释,也会弹出此AlertDialog。我想阻止那个。仅在有注释存在时才弹出AlertDialog。
我想知道是否可以通过某种方法从Adapter类中获取Activity中的RecyclerView大小。我认为这将是实现这一目标的最佳方法。如果有更好的方法,一定要让我知道。
以下是各个类别:
NotesActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.arpansircar.java.notepadapplicationusingmvvm.R;
import com.arpansircar.java.notepadapplicationusingmvvm.databinding.ActivityNotesBinding;
import com.arpansircar.java.notepadapplicationusingmvvm.model.Constants;
import com.arpansircar.java.notepadapplicationusingmvvm.model.INotesActivity;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesDatabase;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesEntity;
import com.arpansircar.java.notepadapplicationusingmvvm.viewmodel.NotesActivityViewModel;
import java.util.List;
import java.util.Objects;
/**
* The NotesActivity is the primary activity in the entire applications.
* This activity starts up and shows the user all the notes that have been created or the facility to add a new note using the floating action button.
* All the notes that have been created using this application and short details associated with them show up in the RecyclerView.
* The user can click on any of these notes to view the complete details of the note.
*/
public class NotesActivity extends AppCompatActivity implements View.OnClickListener,INotesActivity {
private ActivityNotesBinding activityNotesBinding;
private NotesActivityViewModel notesActivityViewModel;
/*The onCreate method is the first method that is executed when the application starts up.
* Usually,in this method,such functions are executed that are to be performed only once.
* In this method,I've defined two other methods to be executed as soon as the application starts up and that are to be executed only once.
* The initializeDatabase() method is used to create an instance of the RoomDatabase.
* An application context is used because we want to use the same instance throughout the context of the application.
* The initializeViewModel() is used to create an instance of the ViewModel class associated with this activity.
* This ViewModel will be used to handle any configuration changes. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityNotesBinding = DataBindingUtil.setContentView(this,R.layout.activity_notes);
initializeDatabase();
initializeViewModel();
}
/*The onStart() is the next method executed after the onCreate() callback method.
* In this method,two methods are executed,namely the setOnClickListenerMethod() and the setObserverMethod().
* The setOnClickListenerMethod() method is tasked with setting the onClickListener for any and all buttons that might exist in the activity.
* Currently,the activity has a single floating action button so this button's onClickListener is set in this activity.
* The setObservableMethod() method is used to activate the Observer to observe changes in the LiveData object present in the ViewModel. */
@Override
protected void onStart() {
super.onStart();
setOnClickListenerMethod();
setObserverMethod();
}
/*The initializeDatabase() method is used to create an instance of the NotesDatabase class.
* This single instance will be used for performing all the database transactions including the CRUD operations.
* For creating an instance of this class,the application context is used.
* I've assumed that using an application context will allow me to use the instance throughout the entirety of the application.*/
private void initializeDatabase() {
NotesDatabase.initializeDatabase(getApplicationContext());
}
/*The initializeViewModel() method is used for initializing the NotesActivityViewModel instance with the ViewModel class.*/
private void initializeViewModel() {
notesActivityViewModel = new ViewModelProvider(this).get(NotesActivityViewModel.class);
}
/*The setObserverMethod() method is used simply for activating the observer.
* This task is done at the Started state of the activity to allow it to start observing the changes in the LiveData as soon as the activity starts.
* If there are any changes in the database,i.e.,if it returns a List of NotesEntity objects,the list is sent to the setRecyclerViewMethod().*/
private void setObserverMethod() {
final Observer<List<NotesEntity>> observer = this::setRecyclerViewMethod;
notesActivityViewModel.selectAllNotesMethod().observe(this,observer);
}
/*The setRecyclerViewMethod(...) is called when the observer observes a change in the LiveData.
* Upon calling this method,the List of NotesEntity objects are passed into this method which promptly passes it to the RecyclerViewAdapter class.
* Accordingly,the RecyclerView is populated with the required views and a new RecyclerView is displayed with the newly added notes.*/
private void setRecyclerViewMethod(List<NotesEntity> notesEntityList) {
RecyclerView recyclerView = activityNotesBinding.notesListRecyclerView;
NotesAdapter notesAdapter = new NotesAdapter(notesEntityList,this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(false);
recyclerView.setAdapter(notesAdapter);
}
/*The setOnClickListenerMethod() is used to set the onClickListener to all the floating action buttons used in the activity.*/
private void setOnClickListenerMethod() {
activityNotesBinding.newNoteFloatingActionButton.setOnClickListener(this);
activityNotesBinding.deleteAllNotesFloatingActionButton.setOnClickListener(this);
}
/*The onClick(...) method allows us to intercept all the clicks placed within this method.
* Since,only a single view can be clicked in this activity,therefore,this method contains only a single if clause.
* The if clause checks if the floating action button has been clicked or not.
* If it has,an Intent object starts the AddEditActivity for the user to add a new note to the activity. */
@Override
public void onClick(View view) {
if (view == activityNotesBinding.newNoteFloatingActionButton) {
Intent newNoteIntent = new Intent(NotesActivity.this,AddEditNoteActivity.class);
newNoteIntent.putExtra("function","insert");
startActivity(newNoteIntent);
}
if (view == activityNotesBinding.deleteAllNotesFloatingActionButton) {
AlertDialog alertDialog = showAlertDialogMethod(
"delete_all",getString(R.string.delete_all_notes_alert_title),getString(R.string.delete_all_notes_alert_message));
alertDialog.show();
}
}
/*The onNoteClicked(...) method here is an overridden method from the INotesActivity interface.
* When a note is clicked in the RecyclerView,the clicked noteID is transferred to this method.
* When this method is triggered,an Intent object is created to start the DisplayNoteActivity.java activity.
* Within this object,the noteID of the clicked note is sent as an Integer extra to next activity.
* Finally,the activity is started.*/
@Override
public void onNoteClicked(NotesEntity notesEntity) {
Intent intent = new Intent(NotesActivity.this,DisplayNoteActivity.class);
intent.putExtra(Constants.COLUMN_ID,notesEntity.getId());
startActivity(intent);
}
private AlertDialog showAlertDialogMethod(String function,String title,String message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.yes_string,(dialogInterface,i) -> {
if (Objects.equals(function,"exit"))
super.onBackPressed();
if (Objects.equals(function,"delete_all"))
notesActivityViewModel.deleteAllNotesMethod();
})
.setNegativeButton(R.string.no_string,i) -> dialogInterface.cancel());
return alertDialogBuilder.create();
}
@Override
public void onBackPressed() {
AlertDialog alertDialog = showAlertDialogMethod(
"exit",getString(R.string.exit_title),getString(R.string.exit_message));
alertDialog.show();
}
}
NotesAdapter.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.arpansircar.java.notepadapplicationusingmvvm.R;
import com.arpansircar.java.notepadapplicationusingmvvm.databinding.IndividualItemsLayoutBinding;
import com.arpansircar.java.notepadapplicationusingmvvm.model.INotesActivity;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesEntity;
import java.util.List;
/**
* The NotesAdapter class is used for setting up the RecyclerView.
* The class accepts a List of NotesEntity objects as the argument for it's constructor.
* This list is used to populate the RecyclerView with newer objects.
*/
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NotesViewHolder> {
private final List<NotesEntity> notesEntityList;
private final INotesActivity iNotesActivity;
public NotesAdapter(List<NotesEntity> notesEntityList,INotesActivity iNotesActivity) {
this.notesEntityList = notesEntityList;
this.iNotesActivity = iNotesActivity;
}
/*The onCreateViewHolder() method configures and returns the views for all the different objects present in the List.*/
@NonNull
@Override
public NotesViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
IndividualItemsLayoutBinding individualItemsLayoutBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()),R.layout.individual_items_layout,parent,false
);
return new NotesViewHolder(individualItemsLayoutBinding,iNotesActivity);
}
/*The onBindViewHolder(...) method receives the views individually from the NotesViewHolder class.
* This method then binds all these individual views to the list.*/
@Override
public void onBindViewHolder(@NonNull NotesViewHolder holder,int position) {
NotesEntity currentNote = notesEntityList.get(position);
holder.individualItemsLayoutBinding.setNoteDetails(currentNote);
}
/*The getItemCount() method simply returns the value denoting the size that our RecyclerView is supposed to be. */
@Override
public int getItemCount() {
if (notesEntityList != null) {
return notesEntityList.size();
} else {
return 0;
}
}
/*The NotesViewHolder class is used to hold each of the views for each of the objects present in the notesEntitiesList list.*/
public class NotesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final IndividualItemsLayoutBinding individualItemsLayoutBinding;
private final INotesActivity iNotesActivity;
public NotesViewHolder(@NonNull IndividualItemsLayoutBinding individualItemsLayoutBinding,INotesActivity iNotesActivity) {
super(individualItemsLayoutBinding.getRoot());
this.individualItemsLayoutBinding = individualItemsLayoutBinding;
individualItemsLayoutBinding.getRoot().setOnClickListener(this);
this.iNotesActivity = iNotesActivity;
}
/*The onClick(...) method is used when we click a particular view present in the RecyclerView.
* When the user clicks on a particular note,this method stores the object for that particular note from the list.
* Next,the noteID is acquired from the object and is sent to the NotesActivity via the INotesActivity interface.*/
@Override
public void onClick(View view) {
iNotesActivity.onNoteClicked(notesEntityList.get(getAdapterPosition()));
}
}
}
感谢您的帮助。
解决方法
这可能有帮助:
if(layoutManager.findViewByPosition(0)==null){
that means recycler view is empty
}
请先进行测试,以确保在非空回收器视图上进行尝试,并确保当第0个位置行不在场景中时不提供null。如果给出非null值,我们很好。同样,如果可行。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。