检查RecyclerView中按下了哪个按钮?

时间:2016-12-08 23:44:41

标签: android firebase android-recyclerview firebase-realtime-database

继上一个问题后,有人建议我使用RecyclerView在我的Android应用程序中显示食谱列表。

我使RecyclerView正常工作(下面的代码),我的RecyclerView的每一行都包含一个配方名称和一个按钮来查看完整的配方。但是我不确定如何检查哪个按钮是正确的,并且还根据单击的按钮显示配方数据。

当其中一个" View"单击按钮,我想启动活动ViewRecipe,如果可能,我想发送" recipeKey"对于新活动的配方,以便我可以从Firebase检索其数据,或者如果我可以在mRecipes ArrayList中获取该配方的索引,则将此索引和mRecipesIds传递给ViewRecipe。然而,这是我第一次使用RecylerView,我不知道如何获取这些值并将它们发送到新活动。

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class RecipeListActivity extends AppCompatActivity {

    ArrayList<Contact> contacts;

    private static final String TAG = "RecipeBook";
    private DatabaseReference mRecipeReference;
    ValueEventListener mRecipeListener;
    RecipeAdapter adapter;
    private RecyclerView mRecipeRecycler;


    private ImageButton Back;
    String recipeKey;
    ArrayList<Recipe> recipeMap = new ArrayList<Recipe>();
    RecyclerView rvContacts;
    private TextView test;
    String name;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipes);

        mRecipeRecycler = (RecyclerView) findViewById(R.id.rvRecipes);

        mRecipeReference = FirebaseDatabase.getInstance().getReference().child("likedrecipe");
        mRecipeRecycler.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    public void onStart() {
        super.onStart();

        ValueEventListener recipeListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot recipeSnapshot: dataSnapshot.getChildren()) {
                    Recipe recipe = recipeSnapshot.getValue(Recipe.class);
                    recipeKey = recipeSnapshot.getKey();
                    recipe.id = recipeKey;
                    name = recipe.Name;
                    recipeMap.add(recipe);
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            }
        };
        mRecipeReference.addValueEventListener(recipeListener);

        mRecipeListener = recipeListener;

        // Listen for comments
        adapter = new RecipeAdapter(this, mRecipeReference);
        mRecipeRecycler.setAdapter(adapter);

    }

    @Override
    public void onStop() {
        super.onStop();

        if (mRecipeListener!= null) {
            mRecipeReference.removeEventListener(mRecipeListener);
        }

        //RecipeAdapter.cleanupListener();
    }

    public static class RecipeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView nameTextView;
        public Button messageButton;

        public RecipeViewHolder(View itemView) {
            super(itemView);

            nameTextView = (TextView) itemView.findViewById(R.id.contact_name);
            messageButton = (Button) itemView.findViewById(R.id.message_button);
            messageButton.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if(v.getId() == messageButton.getId()) {
                //startActivity(new Intent(this, ViewRecipe.class));

            }
        }
    }

    public class RecipeAdapter extends RecyclerView.Adapter<RecipeViewHolder> {

        private List<Recipe> mRecipes = new ArrayList<Recipe>();
        private List<String> mRecipeIds = new ArrayList<String>();

        private Context mContext;
        private DatabaseReference mDatabaseReference;
        private ChildEventListener mChildEventListener;

        public RecipeAdapter(Context context, DatabaseReference ref) {
            mContext = context;
            mDatabaseReference = ref;


            ChildEventListener childEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
                    Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());

                    Recipe recipe = dataSnapshot.getValue(Recipe.class);

                    mRecipeIds.add(dataSnapshot.getKey());
                    mRecipes.add(recipe);
                    notifyItemInserted(mRecipes.size() - 1);
                    // [END_EXCLUDE]
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
                    Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());

                    Recipe newrecipe = dataSnapshot.getValue(Recipe.class);
                    String recipeKey = dataSnapshot.getKey();

                    int recipeIndex = mRecipeIds.indexOf(recipeKey);
                    if (recipeIndex > -1) {
                        mRecipes.set(recipeIndex, newrecipe);

                        notifyItemChanged(recipeIndex);
                    } else {
                        Log.w(TAG, "onChildChanged:unknown_child:" + recipeKey);
                    }
                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {
                    Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());

                    String recipeKey = dataSnapshot.getKey();

                    int recipeIndex = mRecipeIds.indexOf(recipeKey);
                    if (recipeIndex > -1) {
                        mRecipeIds.remove(recipeIndex);
                        mRecipes.remove(recipeIndex);

                        notifyItemRemoved(recipeIndex);
                    } else {
                        Log.w(TAG, "onChildRemoved:unknown_child:" + recipeKey);
                    }

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
                    Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());

                    Recipe movedRecipe = dataSnapshot.getValue(Recipe.class);
                    String recipeKey = dataSnapshot.getKey();

                    // ...
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.w(TAG, "postRecipes:onCancelled", databaseError.toException());
                    Toast.makeText(mContext, "Failed to load recipes.",
                            Toast.LENGTH_SHORT).show();
                }
            };
            ref.addChildEventListener(childEventListener);

            mChildEventListener = childEventListener;
        }


        @Override
        public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View view = inflater.inflate(R.layout.item_recipe, parent, false);
            return new RecipeViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecipeViewHolder holder, int position) {
            Recipe recipe = mRecipes.get(position);
            holder.nameTextView.setText(recipe.Name);
            holder.messageButton.setText("View");
        }

        @Override
        public int getItemCount() {
            return mRecipes.size();
        }

        public void cleanupListener() {
            if (mChildEventListener != null) {
                mDatabaseReference.removeEventListener(mChildEventListener);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

@Override
public void onClick(View v) {
if(v.getId() == messageButton.getId()) {
int position=getAdapterPosition();             
startActivity(new Intent(this, ViewRecipe.class).putExtra("mRecipeId",yourlist.getAdapterPosition()));
            }}

因此,您可以使用getAdapterPosition方法获取单击的位置。然后,您可以从用于扩充列表的列表中传递特定元素。 希望它可以帮到你。