如何将数据从RecyclerView传递到活动

huangapple go评论56阅读模式
英文:

How to pass data from RecyclerView to activity

问题

public class CreateMealPlan extends MainActivity {

    DatePicker datepicker;
    Button submit;
    List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
    SQLiteDatabase db;
    Cursor c;
    RecyclerView recipeList;
    RecipeListAdapter adapterRecipe;
    String recipe_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_meal_plan);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        
        // ... (skipping navigation setup)

        datepicker = findViewById(R.id.calendarView);
        ListRecipes();
        adapterRecipe = new RecipeListAdapter(this, listRecipe);
        recipeList = findViewById(R.id.recipes);
        
        // ... (skipping RecyclerView setup)

        recipeList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("Recipe name is", recipe_name);
            }
        });

        // ... (skipping date handling and submit button click event)
    }

    public void ListRecipes() {
        listRecipe.clear();
        db = (new DatabaseManager(this).getWritableDatabase());
        String selectQuery = "SELECT recipe_name, image, image2, category" +
                             " FROM " + DatabaseManager.TABLE_RECIPE + "  GROUP BY recipe_name";
        c = db.rawQuery(selectQuery, null);
        Log.d("Query", selectQuery);
        if (c.moveToFirst()) {
            do {
                com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
                category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
                category.setImage(c.getInt(c.getColumnIndex("image")));
                category.setImage2(c.getString(c.getColumnIndex("image2")));
                category.setCategory_name(c.getString(c.getColumnIndex("category")));
                listRecipe.add(category);
            } while (c.moveToNext());
            c.close();
        }
    }
}

public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {

    private List<Category> listRecipe;
    private LayoutInflater mInflater;
    private com.stu54259.plan2cook.Adapters.RecipeListAdapter.ItemClickListener mClickListener;

    public RecipeListAdapter(Context context, List<Category> data) {
        this.mInflater = LayoutInflater.from(context);
        this.listRecipe = data;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView1.setText(listRecipe.get(position).getRecipe_name());
        holder.myTextView2.setText(listRecipe.get(position).getCategory_name());
        String image2 = listRecipe.get(position).getImage2();
        Bitmap myBitmap = BitmapFactory.decodeFile(image2);
        if (myBitmap != null)
            holder.imgImage.setImageBitmap(myBitmap);
        else
            holder.imgImage.setImageResource(listRecipe.get(position).getImage());
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView1;
        TextView myTextView2;
        ImageView imgImage;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView1 = itemView.findViewById(R.id.txtName);
            myTextView2 = itemView.findViewById(R.id.txtCategory);
            imgImage = itemView.findViewById(R.id.imgImage);

            myTextView1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String recipe_name = myTextView1.getText().toString();
                }
            });
        }

        @Override
        public void onClick(View v) {
            // Handle click event if needed
        }
    }

    void setClickListener(com.stu54259.plan2cook.Adapters.RecipeListAdapter.ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}
英文:

I'm really struggling with this, what I need is when the user clicks on the recipe image, which comes from the ArrayList listRecipe put into the RecyclerView, the value from myTextView1 should be passed to the CreateMealPlan activity so it can be saved along with the date to an SQLite database.

Hope I've made this clear, thanks in advance for any help.

Activity

    public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List&lt;com.stu54259.plan2cook.Model.Category&gt; listRecipe = new ArrayList&lt;&gt;();
SQLiteDatabase db;
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
adapterRecipe = new RecipeListAdapter(this, listRecipe);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
recipeList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(&quot;Recipe name is&quot;, recipe_name);
}
});
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat(&quot;EEEE&quot;);
Date d_name = new Date(day, month, year);
String dayOfTheWeek = sdf.format(d_name);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
public void ListRecipes() {
listRecipe.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = &quot; SELECT recipe_name, image, image2, category&quot; + &quot; FROM &quot; + DatabaseManager.TABLE_RECIPE + &quot;  GROUP BY recipe_name&quot;;
c = db.rawQuery(selectQuery, null);
Log.d(&quot;Query&quot;, selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex(&quot;recipe_name&quot;)));
category.setImage(c.getInt(c.getColumnIndex(&quot;image&quot;)));
category.setImage2(c.getString(c.getColumnIndex(&quot;image2&quot;)));
category.setCategory_name(c.getString(c.getColumnIndex(&quot;category&quot;)));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
}

RecyclerAdapter

    public class RecipeListAdapter extends RecyclerView.Adapter&lt;com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder&gt; {
private List&lt;Category&gt; listRecipe;
private LayoutInflater mInflater;
private com.stu54259.plan2cook.Adapters.RecipeListAdapter.ItemClickListener mClickListener;
// data is passed into the constructor
public RecipeListAdapter(Context context, List&lt;Category&gt; data) {
this.mInflater = LayoutInflater.from(context);
this.listRecipe = data;
}
// inflates the row layout from xml when needed
@Override
public com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.cardview_recipe, parent, false);
return new com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder holder, int position) {
holder.myTextView1.setText(listRecipe.get(position).getRecipe_name());
holder.myTextView2.setText(listRecipe.get(position).getCategory_name());
String image2 = listRecipe.get(position).getImage2();
Bitmap myBitmap = BitmapFactory.decodeFile(image2);
if (myBitmap != null)
holder.imgImage.setImageBitmap(myBitmap);
else
holder.imgImage.setImageResource(listRecipe.get(position).getImage());
}
// total number of rows
@Override
public int getItemCount() {
return listRecipe.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView1;
TextView myTextView2;
ImageView imgImage;
ViewHolder(View itemView) {
super(itemView);
myTextView1 = itemView.findViewById(R.id.txtName);
myTextView2 = itemView.findViewById(R.id.txtCategory);
imgImage = itemView.findViewById(R.id.imgImage);
myTextView1.setOnClickListener(this);
myTextView1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String recipe_name = myTextView1.getText().toString();
}
});
}
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
@Override
public void onClick(View v) {
}
}
// allows clicks events to be caught
void setClickListener(com.stu54259.plan2cook.Adapters.RecipeListAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}

答案1

得分: 1

你应该:

  1. 定义一个用于处理点击事件的接口(类似于你的ItemClickListener);
  2. 通过匿名类或扩展你的Activity来实现这个接口;
  3. 将这个新接口的实例传递给你的适配器;
  4. 设置点击监听器,处理点击事件并将数据传递回你的Activity。

步骤1:定义一个接口

示例接口:

interface OnRecipeClickListener {
    void onRecipeClicked(int position, String someString);
}

步骤2:实现接口

这部分位于你的Activity类内部:

new OnRecipeClickListener() {
    public void onRecipeClicked(int position, String someString) {
        Log.d(CreateMealPlan.class.getSimpleName(), "Here is the data: " + someString);
    }
}

步骤3:将这个接口传递给适配器

public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {

    ...
    private OnRecipeClickListener clickListener;

    // 数据在构造函数中传递
    public RecipeListAdapter(Context context, List<Category> data, OnRecipeClickListener clickListener) {
        ...
        this.clickListener = clickListener;
    }

    ...
}

步骤4:设置视图持有者的点击监听器

public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {

    ...
        @Override
    public void onBindViewHolder(@NonNull com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder holder, int position) {
        ...
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickListener.onRecipeClicked(position,
                                              holder.textView1.getText().toString());
            } 
        });
    }

    ...
}

从步骤2的代码可以像这样使用:

OnRecipeClickListener listener = new OnRecipeClickListener() {
    public void onRecipeClicked(int position, String someString) {
        Log.d(CreateMealPlan.class.getSimpleName(), "Here is the data: " + someString);
    }
};

adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
英文:

You should:

  1. Define an interface that will be used to handle click events (similar to your ItemClickListener);
  2. Implement this interface as an anonymous class or by extending your Activity;
  3. Pass that instance of the new interface to your adapter;
  4. Set click listener, handle click events and pass data back into your Activity.

Step 1: define an interface

Sample interface:

interface OnRecipeClickListener {
void onRecipeClicked(int position, String someString);
}

Step 2: implement the interface

This part is located inside of your Activity class:

new OnRecipeClickListener() {
public void onRecipeClicked(int position, String someString) {
Log.d(CreateMealPlan.class.getSimpleName(), &quot;Here is the data: &quot; + someString);
}
}

Step 3: passing this interface to the adapter


public class RecipeListAdapter extends RecyclerView.Adapter&lt;com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder&gt; {
...
private OnRecipeClickListener clickListener;
// data is passed into the constructor
public RecipeListAdapter(Context context, List&lt;Category&gt; data, OnRecipeClickListener clickListener) {
...
this.clickListener = clickListener;
}
...
}

Step 4: setting click listeners to view holders


public class RecipeListAdapter extends RecyclerView.Adapter&lt;com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder&gt; {
...
@Override
public void onBindViewHolder(@NonNull com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder holder, int position) {
...
holder.image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clickListener.onRecipeClicked(position,
holder.textView1.getText().toString());
} 
});
}
...
}

Code from Step 2 can be used like that:

OnRecipeClickListener listener = new OnRecipeClickListener() {
public void onRecipeClicked(int position, String someString) {
Log.d(CreateMealPlan.class.getSimpleName(), &quot;Here is the data: &quot; + someString);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);

huangapple
  • 本文由 发表于 2020年9月28日 01:39:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64091448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定