Использование Recycler View для выбора элемента из списка - PullRequest
0 голосов
/ 01 апреля 2020

Для Назначения мне нужно использовать щелчок на представлении переработчика, с этим щелчком у меня есть 2 варианта в диалоговом окне. Это редактировать и удалять. По сути, моя проблема в том, что я не знаю, как определить положение щелчка. Так что я не могу получить детали этого рецепта (название класса). Я использовал LiveData>, поскольку это то, что говорит назначение для использования.

Проблемы, с которыми я сталкиваюсь: 1. Я не знаю, как использовать позицию, чтобы получить правильный рецепт из класса Recipe. 2. Мне нужно использовать List, а не ArrayList

Вот мой основной класс активности

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

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, newRecipeActivity.class);
                startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);
            }
        });

}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
        Recipe recipe = new Recipe(data.getStringExtra(newRecipeActivity.EXTRA_REPLY));
        RecipeViewModel.insert(recipe);
    } else {
        Toast.makeText(
                getApplicationContext(),
                R.string.empty_not_saved,
                Toast.LENGTH_LONG).show();
    }
}


@Override
public void onItemClick(int position) {
    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);
            startActivity(update);
        }
    });
    alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //Delete

        }
    });
    alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
    alertDialog.show();
}
}

Вот мой класс адаптера

 public class RecipeListAdapter extends 
 RecyclerView.Adapter<RecipeListAdapter.RecipeViewHolder> {
private OnItemClickListener mListener;
private LiveData<List<Recipe>> recipeList;



public interface OnItemClickListener{
    void onItemClick(int position);

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

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{}

} Вот моя модель просмотра класс

 public class RecipeViewModel extends AndroidViewModel {

private static RecipeRepository repo;
private LiveData<List<Recipe>> mAllRecipes;

public RecipeViewModel(Application application){
    super(application);
    repo = new RecipeRepository(application);
    mAllRecipes = repo.getAllRecipes();
}
LiveData<List<Recipe>> getAllRecipes() { return mAllRecipes; }
public static void insert(Recipe recipe) { repo.insert(recipe);}

public void getRecipe(int position) {

}
}

1 Ответ

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

Объявите список в MainActivity

List<Recipe> recipesList = new ArrayList<>();

Инициализируйте этот список своими рецептами

mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
            @Override
            public void onChanged(@Nullable final List<Recipe> recipes) {
                recipesList = recipes; //init here
                adapter.setWords(recipes);
            }
        });

Используйте положение, чтобы получить конкретный элемент, который вы хотите отредактировать или удалить

@Override
public void onItemClick(int position) {
    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) {

            recipesList.get(position); //returns the clicked item
            Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
            startActivity(update);
        }
    });
    alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //Delete
            recipesList.get(position); //returns the clicked item
        }
    });
    alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
    alertDialog.show();
}
...