Reputation: 121
I have added a new activity on itemView in recycler view but I want to add multiple activities on individual items. The tutorials are pretty good for Button but I can't figure out how to implement on the itemview. the recyclerview called in MainActivity is as follows;
private String[] channelnames={"PTC Punjabi","Chakde TV","T-Series Punjabi", "9X Tashan", "Zee Punjabi" };
private int[] channelimages={R.drawable.ptcpunjabi, R.drawable.chakde, R.drawable.tseries, R.drawable.ninex, R.drawable.zeepunjabi};
private List<channel> channelList=new ArrayList<>();
thirdrecyclerView=findViewById(R.id.third_recycler_view);
thirdrecyclerView.setHasFixedSize(true);
channelList=new ArrayList<>();
LinearLayoutManager thirdlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
thirdrecyclerView.setLayoutManager(thirdlinearLayoutManager);
for (int i=0;i < channelnames.length;i++){
channel channel=new channel(channelnames[i],channelimages[i]);
channelList.add(channel);
}
the adapter and viewholder class is defined as;
public class channeladpater extends RecyclerView.Adapter<channeladpater.Channelviewholder> {
private List<channel> channelList;
Context ctx;
public channeladpater(List<channel> channelList) {
this.channelList = channelList;
this.ctx=ctx;
}
@NonNull
@Override
public Channelviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false);
return new Channelviewholder(view);
}
@Override
public void onBindViewHolder(@NonNull Channelviewholder holder, int position)
{
channel channel=channelList.get(position);
holder.channelname.setText(channel.getChannelname());
holder.channelimage.setImageResource(channel.getChannelimage());
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onItemClickListener(View v, int position) {
Intent intent=new Intent(ctx, MainActivity2.class);
ctx.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return channelList.size();
}
public static class Channelviewholder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView channelname;
public CircleImageView channelimage;
ItemClickListener itemClickListener;
Channelviewholder(@NonNull View itemView) {
super(itemView);
this.channelname=itemView.findViewById(R.id.profile_name);
this.channelimage=itemView.findViewById(R.id.profile_image);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
this.itemClickListener.onItemClickListener(v,getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic){
this.itemClickListener=ic;
}
}
}
here I want to assign 1st image or textview (PTC punjabi/ R.drawable.ptcpunjabi) to MainActivity 2, the 2nd textview and imageview(Chakde Tv/R.drawable.chakde) to MainActivity 3 and so on. how can I call the text or image view combined to that when the whole card is clicked the next activity starts. the MainActivity 2 is as follows;
public class MainActivity2 extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<VideoDetails> videoDetailsoArrayList;
Intent intent=getIntent();
String API_Key = " ";
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId="+channelID+"&maxResults=50&sort=date&key=[API_KEY]";
com.currentmedia.punjabinews.adapter adapter;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
recyclerView=findViewById(R.id.listView);
videoDetailsoArrayList= new ArrayList<>();
adapter=new adapter(MainActivity2.this,videoDetailsoArrayList);
displayVideos();
}
private void displayVideos ()
{
RequestQueue requestQueue= Volley.newRequestQueue(this);
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("id")){
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
if (jsonVideoId.has("kind")){
if(jsonVideoId.getString("kind").equals("youtube#video")){
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault=jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_id=jsonVideoId.getString("videoId");
VideoDetails vd=new VideoDetails();
vd.setVideoId(video_id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsoArrayList.add(vd);
}
// recyclerView.setAdapter(adapter);
// adapter.notifyDataSetChanged();
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter= new adapter(getApplicationContext(),videoDetailsoArrayList);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(), LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
In the String url, I want to add channelId for the list of channelnames, to avoid adding multiple activites.
PTC punjabi
UCHJW1_0oPzYZl89wX_jhrgA
Chakde Tv
UCaT-WGdJLyEDnxZPAKRTbqQ
T-series punjabi
UCJMSoNjSKRARSIJM3GymRjQ
9x tashan
UCrET5fR2NAUTO2Xp12G0l8A
zee punjabi
UCYF_LfBBxkFBEgaSCNrqW3w
aformentioned is the list of channelIDs I want to assign to them so that when each image is selected from MAin Activity, individual channel activity starts.
Upvotes: 4
Views: 632
Reputation: 66704
It's better to use a listener param or method in Activity and send position or Class
of Activity of item clicked to MainActivity and open Activities based on class is easier and used in Google's examples either.
abstract class BaseAdapter : RecyclerView.Adapter<BaseAdapter.MyViewHolder>() {
private var listener: OnRecyclerViewItemClickListener? = null
inner class MyViewHolder
(// each data item is just a string in this case
private val binding: ViewDataBinding
) : RecyclerView.ViewHolder(binding.root), View.OnClickListener {
internal fun bind(obj: Any) {
binding.setVariable(BR.obj, obj)
binding.executePendingBindings()
// Set click listener
itemView.setOnClickListener(this)
}
override fun onClick(v: View) {
listener?.run {
onItemClicked(v, layoutPosition)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
// create a new view
val layoutInflater = LayoutInflater.from(parent.context)
val binding =
DataBindingUtil.inflate<ViewDataBinding>(
layoutInflater,
getLayoutIdForType(viewType),
parent,
false
)
// set the view's size, margins, paddings and layout parameters
return MyViewHolder(binding)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(getDataAtPosition(position))
}
/**
* Get data in position for RecyclerView row. This method is invoked inside
* onBindViewHolder() method of RecyclerView
*
* @param position indicates the item for the current row
* @return data for the current row
*/
abstract fun getDataAtPosition(position: Int): Any
/**
* Get id of layout from R. This method is invoked from onCreateViewHolder method of Adapter
*
* @param viewType id of layout row of RecyclerView
* @return id of layout
*/
abstract fun getLayoutIdForType(viewType: Int): Int
/**
* RecyclerViewClickListener interface helps user to set a clickListener to the
* RecyclerView. By setting this listener, any item of Recycler View can respond
* to any interaction.
*/
interface OnRecyclerViewItemClickListener {
/**
* This is a callback method that be overridden by the class that implements this
* interface
*/
fun onItemClicked(view: View, position: Int)
}
fun setOnItemClickListener(listener: OnRecyclerViewItemClickListener) {
this.listener = listener
}
}
Data that contains class name and optional description
data class ActivityClassModel(val clazz: Class<*>, val description: String = clazz.name)
Adapter implementation
class ChapterSelectionAdapter(private val data: List<ActivityClassModel>) : BaseAdapter() {
override fun getDataAtPosition(position: Int): Any {
return data[position]
}
override fun getLayoutIdForType(viewType: Int): Int {
return R.layout.row_layout
}
override fun getItemCount(): Int {
return data.size
}
}
MainActivity
class MainActivity : AppCompatActivity(), BaseAdapter.OnRecyclerViewItemClickListener {
private val activityClassModels = ArrayList<ActivityClassModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activityMainBinding =
DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
// Add Activities to list to be displayed on RecyclerView
activityClassModels.add(
ActivityClassModel(
Activity1Basics::class.java,
"Activity BottomNavigationView with listener"
)
)
val recyclerView = activityMainBinding.recyclerView
recyclerView.apply {
// Use fixed size for performance
setHasFixedSize(true)
// use a linear layout manager
layoutManager = LinearLayoutManager(this@MainActivity)
// Add vertical divider
addItemDecoration(
DividerItemDecoration(
this@MainActivity,
DividerItemDecoration.VERTICAL
)
)
// Add Adapter
recyclerView.adapter = ChapterSelectionAdapter(activityClassModels).apply {
setOnItemClickListener(this@MainActivity)
}
}
}
@Override
override fun onItemClicked(view: View, position: Int) {
Intent(this@MainActivity, activityClassModels[position].clazz).also {
startActivity(it)
}
}
}
Upvotes: 1
Reputation: 1595
If you have 10 items in the list you don't need to create 10 activities for each item.
All you need is one same activity for showing details from the list in MainActivity.
When you press the item in list, you need to pass it's position
and data(channel
in your case) to the SecondActivity using Intents
.
So let's make these changes.
In your adapter class:
You have setup the listener but make sure you are passing data.
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onItemClickListener(View v, int position) {
Intent intent = new Intent(ctx, MainActivity2.class);
// Using intent pass your data to MainActivity2 class
intent.putExtra("Intent to MainActivity2", channel);
ctx.startActivity(intent);
}
});
MainActivity2 class :
Now you have to receive data from previous activity.
In your onCreate()
of the activity after inflating the layout and before setting any views.
Channel channel = getIntent().getParcelableExtra("Intent to MainActivity2");
From above code you are getting the data from which this intent has received, you may have received data from any activity too, so to specific from activity you refer using the String
inside getParcelableExtra()
Now after getting data, call it's properties this way
yourTextView.setText(channel.channelname)
That's it. Now you can see clicking each item from list from previous activity and no more need extra activities.
For your reference you can see this project follows similar approach.
Upvotes: 2