使用多个 onclick 侦听器将多个 url 传递给 recyclerview 中的 itemview
Posted
技术标签:
【中文标题】使用多个 onclick 侦听器将多个 url 传递给 recyclerview 中的 itemview【英文标题】:Pass multiple urls to itemview in recyclerview using multiple onclick listeners 【发布时间】:2021-01-05 15:49:14 【问题描述】:在我的 onBindViewholder 中,我将 onclickListener 传递给回收站视图中的 itemview。 Itemview 由一个带有图像和文本的数组组成; 主要活动
public class MainActivity extends AppCompatActivity
private AdView mAdView;
private AdView mAdView2;
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView firstrecyclerView;
private RecyclerView thirdrecyclerView;
ArrayList<itemModel> items;
String[] iconName = "ABP Sanjha","Breaking News Punjab","Republic Bharat", "Al Jazeera","DW News","Sky News","Indus Live","CNA","RT News";
//cannel icons and names
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 String[] channelID="UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w";
private List<channel> channelList=new ArrayList<>();
//youtube player fragment
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private ArrayList<String> youtubeVideoArrayList;
private YouTubePlayer youTubePlayer;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateDummyVideoList();
initializeYoutubePlayer();
setUpRecyclerView();
populateRecyclerView();
MobileAds.initialize(this, new OnInitializationCompleteListener()
@Override
public void onInitializationComplete(InitializationStatus initializationStatus)
);
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView2 = findViewById(R.id.adView2);
AdRequest adRequest2 = new AdRequest.Builder().build();
mAdView2.loadAd(adRequest2);
/**
* initialize youtube player via Fragment and get instance of YoutubePlayer
*/
private void initializeYoutubePlayer()
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener()
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored)
if (!wasRestored)
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
@Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1)
//print or show error if initialization failed
Log.e(TAG, "Youtube Player View initialization failed");
);
// setup the recycler view here
private void setUpRecyclerView()
firstrecyclerView = findViewById(R.id.first_recycler_view);
firstrecyclerView.setHasFixedSize(true);
items = new ArrayList<>();
//Horizontal direction recycler view
LinearLayoutManager firstlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
firstrecyclerView.setLayoutManager(firstlinearLayoutManager);
firstrecyclerView.setItemAnimator(new DefaultItemAnimator());
for (int i = 0; i < iconName.length; i++)
itemModel itemModel = new itemModel(iconName[i], youtubeVideoArrayList.get(i));
items.add(itemModel);
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);
//populate the recycler view and implement the click event here
private void populateRecyclerView()
final CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
//set click event
firstrecyclerView.addOnItemTouchListener(new RecyclerViewOnClickListener(this, new RecyclerViewOnClickListener.OnItemClickListener()
@Override
public void onItemClick(View view, int position)
if (youTubePlayerFragment != null && youTubePlayer != null)
//update selected position
adapterf.setSelectedPosition(position);
//load selected video
youTubePlayer.cueVideo(youtubeVideoArrayList.get(position));
));
channeladpater channeladpater=new channeladpater(channelList);
thirdrecyclerView.setAdapter(channeladpater);
//method to generate dummy array list of videos
private void generateDummyVideoList()
youtubeVideoArrayList = new ArrayList<>();
//get the video id array from strings.xml
String[] videoIDArray = getResources().getStringArray(R.array.video_id_array);
//add all videos to array list
Collections.addAll(youtubeVideoArrayList, videoIDArray);
现在我尝试在以这种方式单击 itemview 时打开另一个活动; channeladapter 类;
public class channeladpater extends RecyclerView.Adapter<channeladpater.Channelviewholder>
private List<channel> channelList;
Context ctx;
public channeladpater(List<channel> channelList)
this.channelList=channelList;
@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)
final 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)
final String[] channelID="UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w";
Intent intent=MainActivity2.newIntent(v.getContext(), channelID);
v.getContext().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;
新的活动开始基本上是使用 youtube 数据 api 获取的视频列表; MainActivity2
public class MainActivity2 extends AppCompatActivity
RecyclerView recyclerView;
ArrayList<VideoDetails> videoDetailsoArrayList;
public static String CHANNEL_ID_EXTRA = "channel_id_extra";
public static Intent newIntent(Context context, String[] channelID)
return new Intent(context, MainActivity2.class).putExtra(CHANNEL_ID_EXTRA, channelID);
String API_Key = "AIzaSyA1_spJ4XGWOCekBLCsSAgWderHHl_46m0";
private String[] channelID="UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w";
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId="+ Arrays.toString(channelID) +"&maxResults=50&sort=date&key=AIzaSyA1_spJ4XGWOCekBLCsSAgWderHHl_46m0";
adapter adapter;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final String channelID = getIntent().getStringExtra(CHANNEL_ID_EXTRA);
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);
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);
现在我正在尝试从 MainActivity2 的字符串 url 更改 channelID,这样当单击带有字符串 channelnames "PTC Punjabi" 的 itemview 时,MainActivity 被加载channelID "UCHJW1_0oPzYZl89wX_jhrgA",当channelnames "Chakde Tv" 被点击时,MainActivity2 被加载 channelID "UCaT-WGdJLyEDnxZPAKRTbqQ" 等等。但我不明白如何将 channelId 列表传递给 MainActivity2? 我应该在 MainActivity 中声明 channelId 数组吗?请有人在这一步指导我。我知道解决方案很小,因为我已经看过有关按钮活动的教程,但我无法理解将 url 传递给其他活动。 渠道模型类
public class channel
String channelname;
int channelimage;
public channel(String channelname, int channelimage)
this.channelname = channelname;
this.channelimage = channelimage;
public String getChannelname()
return channelname;
public int getChannelimage()
return channelimage;
【问题讨论】:
【参考方案1】:首先:在其他地方创建Intent
然后创建您正在创建的意图的活动不是一个好习惯。
所以你需要在你的 MainActivity2 中添加静态方法:
public static String CHANNEL_ID_EXTRA = "channel_id_extra";
public static Intent newIntent(Context context, String channelID)
return new Intent(context, MainActivity2.class).putExtra(CHANNEL_ID_EXTRA, channelID);
之后你可以通过onCreate()
方法获取这个ID:
final String channelId = getIntent().getStringExtra(CHANNEL_ID_EXTRA);
现在在 Holder 中:在此编辑
@Override
public void onBindViewHolder(@NonNull Channelviewholder holder, int position)
final 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)
final String channelID= channelList.get(position);
Intent intent=MainActivity2.newIntent(v.getContext(), channelID);
v.getContext().startActivity(intent);
);
【讨论】:
但是我有一个channelID列表..如何事先声明它们,以便根据点击分配该字符串的每个项目PTC punjabi UCHJW1_0oPzYZl89wX_jhrgA Chakde Tv UCaT-WGdJLyEDnxZPAKRTbqQ T-series punjabi UCJMSoNjSKRARSIJM3GymRjQ 9x tashan UCrET5fR2NAUTO2Xp12G0l8A zee punjabi UCYF_LfBBxkFBEgaSCNrqW3w
这是我希望通过 5 次单独点击传递的列表
这没有分配任何 ID
@summyiaharis 如何为您的适配器创建项目列表?
` holder.setItemClickListener(new ItemClickListener() @Override public void onItemClickListener(View v, int position) final String[] channelID="UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w"; Intent intent=MainActivity2.newIntent(v.getContext(), channelID); v.getContext().startActivity(intent); );`以上是关于使用多个 onclick 侦听器将多个 url 传递给 recyclerview 中的 itemview的主要内容,如果未能解决你的问题,请参考以下文章
在 Android 中以编程方式创建的多个文本视图的单个 onclick 侦听器