如何在RecycleView中实现onclick侦听器到卡片

时间:2017-09-20 04:33:39

标签: java android android-recyclerview onclicklistener

我正在尝试在回收视图中向我的卡片添加onclick监听器,目的是在我点击卡片时转到新的页面/活动。不幸的是,我对Java很新,但仍然不太懂。我看过许多类似的问题,但无法弄清楚如何使用它。 这是我的RecycleView适配器,它还包含View Holder。

public class JobListRecyclerAdapter extends RecyclerView.Adapter<JobListRecyclerAdapter.jobViewHolder> {

    private ArrayList<JobClass> jobClassList;


    public JobListRecyclerAdapter(ArrayList<JobClass> rList) {
        this.jobClassList = rList;

    }

    @Override
    public int getItemCount() {
        if(jobClassList == null){return 0;}
        return jobClassList.size();
    }

    @Override
    public jobViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View itemView = LayoutInflater.
                from(viewGroup.getContext()).
                inflate(R.layout.job_list_card, viewGroup, false);
        return new jobViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(jobViewHolder jobViewHolder, int position) {
        JobClass ci = jobClassList.get(position);
        jobViewHolder.jName.setText("Name: "+ci.getmJobNum());
        jobViewHolder.jDate.setText("Quantity: "+ci.getmJobDate());
    }

    public static class jobViewHolder extends RecyclerView.ViewHolder  {

        protected TextView jName;
        protected TextView jDate;


        public jobViewHolder(View j) {
            super(j);

            jName =  (TextView) j.findViewById(R.id.job_name);
            jDate = (TextView)  j.findViewById(R.id.job_due_date);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mClickListener.onItemClick(v, getAdapterPosition());

                }
            });
        }

        private jobViewHolder.ClickListener mClickListener;

        //Intreface to send callbacks
        public interface ClickListener{
            public void onItemClick(View view, int position);
        }
        public void setOnClickListener(jobViewHolder.ClickListener clicklistener){
            mClickListener = clicklistener;
        }
    }

    }

这是一个名为Job List的活动,它是一个片段,这就是为什么我找不到相关的例子。这是我的主要问题,我不知道如何实现视图,并在点击卡片时进行活动。

public class JobList extends Fragment {

    public JobList() {
    }
    public static JobList newInstance() {
        JobList fragment = new JobList();

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView =  inflater.inflate(R.layout.fragment_job_list, container, false);
        final RecyclerView recyclerView = (RecyclerView)rootView.findViewById(R.id.job_list_recycler_view);

        LinearLayoutManager llm = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(llm);
        final ArrayList<JobClass> joblistclass  = new ArrayList<>();
        /*
        // Create a new Adapter
        final ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_list_item_1, android.R.id.text1);
            */

        // Get a reference to the todoItems child items it the database
        //String userPath = ((GlobalData) getActivity().getApplication()).getUserPath() +"JOBS";
        //final DatabaseReference myRef = database.getReference(userPath);
       // final DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("USERS/04950F4AE53F80/JOBS");
        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference jobsRef = rootRef
                .child("USERS")
                .child("04950F4AE53F80")
                .child("JOBS");
        // Assign a listener to detect changes to the child items
        // of the database reference.
       // myRef.addValueEventListener(new ValueEventListener() {
        ValueEventListener eventListener = new ValueEventListener() {


            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    String jobDate = ds.child("JOBOVERVIEW").child("jobDate").getValue(String.class);
                    JobClass jblst = ds.child("JOBOVERVIEW").getValue(JobClass.class);
                    joblistclass.add(jblst);

                    Log.d("TAG", jobDate);
                }
                final JobListRecyclerAdapter adapterb = new JobListRecyclerAdapter(joblistclass);

                recyclerView.setAdapter(adapterb);

            }
            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };
        jobsRef.addListenerForSingleValueEvent(eventListener);


     ///to send to next page
        Button nextPage = (Button) rootView.findViewById(R.id.addNewJob);

        // Capture button clicks
        nextPage.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Start NewActivity.class
                Intent myIntent = new Intent(getContext(), JobForm.class);
                startActivity(myIntent);
            }
        });


        // go to job page when clicked
        recyclerView.setOnItemClickListener(new View.OnClickListener{
            @Override
            public void onClick(AdapterView<?> adapter, View view, int position, long id) {
                String name = (String) listView.getItemAtPosition(position);
                ((GlobalData) getActivity().getApplication()).setJobId(name);
                // use -((GlobalData) getActivity().getApplication()).getJobId() to refer to the job id
                Intent goToJob = new Intent(getContext(), Main2Activity.class);
                startActivity(goToJob);
            }
        });


        return rootView;
    }

}

Main2Activity是我需要访问的页面。

public class Main2Activity extends AppCompatActivity {

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment2 = null;
            switch (item.getItemId()) {
                case R.id.navigation2_home://maybe edit so that it goes back to first activity
                    selectedFragment2 = HomePage.newInstance();
                    break;
                case R.id.navigation_overview:
                    selectedFragment2 = Overview.newInstance();
                    break;
                case R.id.navigation_safety:
                    selectedFragment2 = Safety.newInstance();
                    break;
                case R.id.navigation_quality:
                    selectedFragment2 = Quality.newInstance();
                    break;
                case R.id.navigation_instruction:
                    selectedFragment2 = Instructions.newInstance();
                    break;
            }
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.content2, selectedFragment2);
            transaction.commit();
            return true;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation2);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

}

上述所有代码中的一切都没问题,我需要帮助Pleeeeeaaaase。

1 个答案:

答案 0 :(得分:1)

在您的JobListRecyclerAdapter班级中,将其更改为:

    public static class jobViewHolder extends RecyclerView.ViewHolder  {

    protected TextView jName;
    protected TextView jDate;
    protected CardView cardView;


    public jobViewHolder(View j) {
        super(j);

        jName =  (TextView) j.findViewById(R.id.job_name);
        jDate = (TextView)  j.findViewById(R.id.job_due_date);
        cardView = (CardView) j.findViewById(R.id.your_card_view_id);

        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Your Code Here

            }
        });
    }

希望这会有所帮助。