简体   繁体   中英

How to get details when clicking on an item in a RecyclerView?

I am trying to get the details of the Recipe from which Recipe I have clicked in recycler view. I am using this to go to an edit/delete feature. Here is the code for my main activity.

The details that I am trying to get is getting the Name, Ingredients and method.

public class MainActivity extends AppCompatActivity implements RecipeListAdapter.OnItemClickListener  {
    private RecipeViewModel mRecipeViewModel;
    public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
    public String Name;
    public String Ingredients;
    public String Method;
    private RecipeListAdapter mAdapter;
    private RecipeDao recDao;
    private LiveData<List<Recipe>> RecipeList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        final RecipeListAdapter adapter = new RecipeListAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(MainActivity.this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);

        mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
            @Override
            public void onChanged(@Nullable final List<Recipe> recipes) {
                // Update the cached copy of the words in the adapter.
                adapter.setWords(recipes);
            }
        });

        void onItemClick(int position) {
        //Delete Below test to pass data through
        Recipe recipe = new Recipe("Test", "Yeet", "Jim");


   // showAlertDialogBox();
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
    alertDialog.setTitle("Edit or Delete...");
    alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
            update.putExtra("Name", recipe.getName());
            update.putExtra("Ingredients", recipe.getIngredients());
            update.putExtra("Method", recipe.getMethod());
            startActivity(update);
        }
    });
    alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //Delete
        }
    });
    alertDialog.show();
}

Here is the Recipe.class if you needed it!

@Entity(tableName = "recipe_table")
public class Recipe {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name= "recipeId")
private int RecipeId;
private String name;
private String Ingredients;
private String Method;
@Ignore
public Recipe(String name, String Ingredients, String Method) {
    this.RecipeId = RecipeId;
    this.name = name;
    this.Ingredients = Ingredients;
    this.Method = Method;
}

public Recipe(String name) {
    this.name = name;
}

public void changeText1(String text){
    name = text;
}

//Add Image somehow!


public int getRecipeId() {
    return RecipeId;
}

public void setRecipeId(int recipeId) {
    RecipeId = recipeId;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getMethod() {
    return Method;
}

public void setMethod(String method) {
    Method = method;
}

public String getIngredients() {
    return Ingredients;
}

public void setIngredients(String ingredients) {
    Ingredients = ingredients;
}
}

If you need anymore files, these are the files I have: - RecipeListAdapter - RecipeDao - RecipeRepository - RecipeRoomDatabase - RecipeViewModel

Recipe Adapter code

public class RecipeListAdapter extends RecyclerView.Adapter { private OnItemClickListener mListener; private List recipeList;

public interface OnItemClickListener{
    void onItemClick(int position, Recipe recipe);

}
public void setOnItemClickListener(OnItemClickListener listener){
    mListener = listener;
}





class RecipeViewHolder extends RecyclerView.ViewHolder {
    private final TextView recipeItemView;

    private RecipeViewHolder(View itemView) {
        super(itemView);
        recipeItemView = itemView.findViewById(R.id.textView);
        itemView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (mListener != null){
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION){
                        mListener.onItemClick(position, 
  recipeList.get(getAdapterPosition()));
                    }
                }
            }
        });
    }
}

private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words

RecipeListAdapter(Context context) {
    mInflater = LayoutInflater.from(context);
    this.recipeList = recipeList;
}

@Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = mInflater.inflate(R.layout.recyclerview_item, parent, 
false);
    return new RecipeViewHolder(itemView);
}

@Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
    if (mRecipes != null) {
        Recipe current = mRecipes.get(position);
        holder.recipeItemView.setText(current.getName());
    } else {
        // Covers the case of data not being ready yet.
        holder.recipeItemView.setText("No Recipes");
    }
}

void setWords(List<Recipe> recipes){
    mRecipes = recipes;
    notifyDataSetChanged();
}

// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't 
return null).
@Override
public int getItemCount() {
    if (mRecipes != null)
        return mRecipes.size();
    else return 0;
}
public interface OnNoteListener{}
}

Inside the onItemClick there is one more parameter need to add.

void onItemClick(int position, Recipe recipe) {
        //Delete selected recipe from recipe list
        arrayList.remove(recipe)
}

The onItemClick method will get called from adapter, from there you have to pass the selected receipe. In the adapter you have to use recipeList.get(getAdapterPosition()) to get the clicked receipe and pass this to the interface method, onItemClick along with the position.

So your code will look like this way inside the adapter,

itemClickListener.onItemClick(position, recipeList.get(getAdapterPosition()))

Just as a note, please ensure instead of List, you need to take ArrayList to perform remove operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM