Java how to start activity in adapter android

Java how to start activity in adapter android

To start an activity from an adapter in Android, you can use the startActivity method of the Context class and pass it an Intent that specifies the activity to be started.

Here's an example of how you can do this in a RecyclerView adapter:

refer to:‮.iruttual‬com
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private List<Item> items;
    private Context context;

    public MyAdapter(Context context, List<Item> items) {
        this.context = context;
        this.items = items;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final Item item = items.get(position);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ExampleActivity.class);
                context.startActivity(intent);
            }
        });
    }
}

This code will start the ExampleActivity activity when the user clicks on an item in the RecyclerView.

Alternatively, you can use the startActivity method of the Activity class to start the activity. To do this, you will need to pass a reference to the activity to the adapter, either as a constructor argument or by using a setter method.

Created Time:2017-11-03 23:27:12  Author:lautturi