Как получить подробную информацию при нажатии на элемент в RecyclerView? - PullRequest
0 голосов
/ 01 апреля 2020

Я пытаюсь получить информацию о рецепте, по которому я щелкнул рецепт, в представлении переработчика. Я использую это для go для функции редактирования / удаления. Вот код для моей основной деятельности.

Подробности, которые я пытаюсь получить, - это получение Имени, Ингредиентов и метода.

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();
}

Вот класс Recipe.class, если он вам нужен!

@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;
}
}

Если вам больше нужны файлы, у меня есть следующие файлы: - RecipeListAdapter - RecipeDao - RecipeRepository - RecipeRoomDatabase - RecipeViewModel

Код адаптера рецепта

publi c Класс RecipeListAdapter расширяет RecyclerView.Adapter {private OnItemClickListener mListener; приватный список 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{}
}

1 Ответ

0 голосов
/ 01 апреля 2020

Внутри onItemClick есть еще один параметр, который необходимо добавить.

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

Метод onItemClick будет вызван из адаптера, после чего вам нужно будет передать выбранный рецепт. В адаптере вы должны использовать recipeList.get (getAdapterPosition ()) , чтобы получить клик по рецепту и передать его методу интерфейса, onItemClick вместе с позицией.

Таким образом, ваш код будет выглядит так внутри адаптера,

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

В качестве примечания, пожалуйста, убедитесь, что вместо Список, вам нужно взять ArrayList для выполнения операции удаления.

...