首页 > 解决方案 > 来自适配器类的访问意图

问题描述

我正在尝试获取一个适配器类来获取存储在另一个适配器类中的意图。这个想法是第一个适配器类将存储一个意图并启动第二个适配器类(Player_Adapter)的活动,如下所示:

public static class NBAViewHolder extends RecyclerView.ViewHolder {
        public LinearLayout containerView;
        public TextView textView;

        NBAViewHolder(View view) {

            super(view);

            containerView = view.findViewById(R.id.nba_row);
            textView = view.findViewById(R.id.nba_row_text_view);

            containerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) { //on clicking the TEAMS will transfer the url to the "TEAMSActivity" class
                    TEAMS current = (TEAMS) containerView.getTag();
                    //an intent is a "glue" between activities, connecting them. He`re the intent is transferring the
                    //url that contains the properties of the TEAMS to the class "TEAMSActivity".
                    //can possibly create a new adapter class
                    Intent intent = new Intent(v.getContext(), com.example.player.Player_Adapter.class);
                    //we get the "fullName"
                    intent.putExtra("id", current.getId());
                    v.getContext().startActivity(intent);
                }
            });
        }
    }

我的问题是我无法使用第二个适配器类中的 getIntent() 函数。我注意到我能够在另一个扩展“AppCompatActivity”的类中使用该函数。我还从另一个线程中读到该函数不是适配器类的一部分。有没有办法解决?我知道我可以只有一个适配器类用于多个活动,但首先我想解决这个问题,谢谢。

标签: javaandroidandroid-intentadapter

解决方案


检查你的身份证!是空的吗?和小指导方针:在 recyclerview.adapter 中创建一个接口,在父活动(适配器放置的位置)中实现该接口,然后将您的活动实例作为创建的接口传递给适配器,并在 onclick 侦听器中使用它。这个想法是将意图的逻辑传递给活动。界面:

public interface TeamClicker{
void onTeamClicked(int teamId);
}
  1. 在适配器之上创建它。
  2. 创建接口变量。
  3. 在您的活动中实现该接口。
  4. 将适配器内部的活动实例作为接口传递,并将其放入您创建的变量中。
  5. 在 onclickListener 中使用该接口。

推荐阅读