如何从recyclerview获取位置并使用它获取Firebase数据的密钥

时间:2019-03-17 12:12:32

标签: android firebase android-recyclerview

我有一个recyclerview,通过选择单选按钮,可以打开一个带有选项的Alertdialog。我的问题是获取所选行(单选按钮)在recyclerview中的位置,因此我可以用它从firebase读取并将其传递给alertdialog。

我的单选按钮onclick方法用于RecyclerView.ViewHolder类。这是我要获取所选单选按钮的位置的地方。

RecyclerView onClick

我已经阅读了上面的链接,因为从总体上来说我是recyclerview和android的新手,所以上面的链接中的解决方案使我感到困惑,这确实令人头疼,他们尝试了大多数解决方案,但仍然找不到我的解决方案< / p>

主要活动

public class Review2 extends AppCompatActivity {
    private TextView impres, impress1, impress2,impress3,impress4,impress5;
    private RecyclerView patient_drug_list;
    private FirebaseAuth mAuth;
    private DatabaseReference mDrugList, mNameDiag, mName;
    private  TextView desker, name, dater;
    public String drug, dosing;
    FirebaseRecyclerAdapter<Drugs, DrugsViewHolder> adapter;

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

        ///Firebase Authentication and related properties
        mAuth = FirebaseAuth.getInstance();
        FirebaseUser mUser = mAuth.getCurrentUser();
        String uId = mUser.getUid();/// id or users

        desker = findViewById(R.id.desk);

        String user_id = getIntent().getStringExtra(Review1.REVIEW_ID);///retrieve value from activity
        ///Toast.makeText(this, user_id, Toast.LENGTH_LONG).show();///verify if value is gotten
        Query query = FirebaseDatabase.getInstance().getReference().child("Drugs").child(uId).child(user_id);
        query.keepSynced(true);

        patient_drug_list = (RecyclerView) findViewById(R.id.recycler2); ////Recycler view from xml
        patient_drug_list.setLayoutManager(new LinearLayoutManager(this));
        patient_drug_list.setHasFixedSize(true);



        ///////////////////////////Assign Items
        impres = findViewById(R.id.diagnose1);
        impress1 = findViewById(R.id.diagnose2);
        impress2 = findViewById(R.id.diagnose3);
        impress3 = findViewById(R.id.diagnose4);
        impress4 = findViewById(R.id.diagnose5);
        impress5 = findViewById(R.id.diagnose6);

        name = findViewById(R.id.RName);
        dater = findViewById(R.id.RDate);


        /////////////Reading firebase data


        mNameDiag = FirebaseDatabase.getInstance().getReference().child("Diagnosis").child(uId).child(user_id);
        mNameDiag.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String diagnosis1 = dataSnapshot.child("diagnosis1").getValue().toString();
                String diagnosis2 = dataSnapshot.child("diagnosis2").getValue().toString();
                String diagnosis3 = dataSnapshot.child("diagnosis3").getValue().toString();
                String diagnosis4 = dataSnapshot.child("diagnosis4").getValue().toString();
                String diagnosis5 = dataSnapshot.child("diagnosis5").getValue().toString();


                impres.setText(diagnosis1);
                impress1.setText(diagnosis2);
                impress2.setText(diagnosis3);
                impress3.setText(diagnosis4);
                impress4.setText(diagnosis5);
                impress5.setText(diagnosis5);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });



        /////////////////////////////////////////////////////////////////
        mName = FirebaseDatabase.getInstance().getReference().child("Patients").child(uId).child(user_id);
        mName.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String namer = dataSnapshot.child("name").getValue().toString();
                String dater1 = dataSnapshot.child("date").getValue().toString();

                name.setText(namer);
                dater.setText(dater1);
                adapter.startListening();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });



                ////Firebase Adapter and related properties

        FirebaseRecyclerOptions<Drugs> options = new FirebaseRecyclerOptions.Builder<Drugs>()
                .setQuery(query, Drugs.class).build();

        adapter = new FirebaseRecyclerAdapter<Drugs, DrugsViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull DrugsViewHolder holder, final int position, @NonNull Drugs model) {
                holder.setDiag1(model.getBrand());
                holder.setDiag2(model.getGeneric());
                holder.setDiag3(model.getDose());
                holder.setDiag4(model.getFrequency1(), model.getFrequency2(), model.getDuration());






            }

            @NonNull
            @Override
            public DrugsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

                ////Recycler view item
                View view = LayoutInflater.from(viewGroup.getContext())
                        .inflate(R.layout.drug_display_list,viewGroup,false);///
                return new DrugsViewHolder(view);
            }
        };

        patient_drug_list.setLayoutManager(new LinearLayoutManager(this));
        patient_drug_list.setAdapter(adapter);//// setting adapter
        adapter.notifyDataSetChanged();
        adapter.startListening();
    }

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
        adapter.notifyDataSetChanged();
    }




////////////////click for new option activities

           //This is a switch for the adio button options that appear after the above radiobutton
    public void clickers(View view) {
        switch (view.getId()){
            case  R.id.drug_needed:
                startActivity(new Intent(getApplicationContext(),Drug_needed.class));
                break;


            case R.id.wrong_drug:
                Toast.makeText(Review2.this, "2nd", Toast.LENGTH_SHORT).show();
                break;

            case R.id.dose_related:
                startActivity(new Intent(getApplicationContext(),Dose.class));
                break;
            case R.id.adverse_reaction:
                startActivity(new Intent(getApplicationContext(),ADR.class));
                break;

            case R.id.food_interaction:
                Toast.makeText(this, "yet to do", Toast.LENGTH_SHORT).show();
                break;

            default:
                Toast.makeText(Review2.this, "nothing to see", Toast.LENGTH_SHORT).show();
                break;
        }
    }


    ////////////////View Holder

    private class DrugsViewHolder extends  RecyclerView.ViewHolder{
        View mView;
        DrugsViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;

            final RadioButton radioButton = mView.findViewById(R.id.not_appropriate);
            radioButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final int position1 = getAdapterPosition();
                    AlertDialog.Builder myDialog = new AlertDialog.Builder(Review2.this);
                    LayoutInflater inflater = LayoutInflater.from(Review2.this);
                    View myview = inflater.inflate(R.layout.adr_options, null);
                    myDialog.setView(myview);
                    myDialog.show();

                }
            });



        }



        void setDiag1(String diag1){
            TextView postdiag1 = mView.findViewById(R.id.brand);
            postdiag1.setText(diag1);

        }
        void setDiag2(String diag2){
            TextView postdiag2 = mView.findViewById(R.id.generic);
            postdiag2.setText(diag2);
            postdiag2.setTextSize(12);
        }
        public void setDiag3(String diag3){
            TextView postdiag3 = mView.findViewById(R.id.dose);
            postdiag3.setText("Dose:" + diag3);
        }
        public void setDiag4(String diag4, String diag5, String diag6){
            TextView postdiag4 = mView.findViewById(R.id.frequency);
            postdiag4.setText("Frequency:" + diag4 + " tab " + diag5+"x" + "daily for "+diag6 + "days");
        }
    }
}

因此,为了简单起见,我只希望能够从RecyclerView.ViewHolder类中使用选定的单选按钮获取recyclerview行的位置。任何建议,想法或示例都将不胜感激。

1 个答案:

答案 0 :(得分:1)

我怎么看:

  1. 您可以使用内部ViewHolder类创建自己的适配器。因此您可以从ViewHolder更改适配器的字段;
  2. 在适配器内创建selectedRowPositionselectedRowsPositions字段;
  3. 更改单选按钮的状态时更改selectedRowPosition
  4. 在需要时阅读适配器的selectedRowPosition字段。

更新

当您看到上述策略时,我已经创建了repository。最重要的类是适配器:

public class RadioButtonsAdapter extends RecyclerView.Adapter<RadioButtonsAdapter.RadioViewHolder> {

    // Field when we store position of last clicked item
    private int lastClickedItemPosition;

    @NonNull
    @Override
    public RadioViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RadioButton button = new RadioButton(parent.getContext());
        return new RadioViewHolder(button);
    }

    @Override
    public void onBindViewHolder(@NonNull RadioViewHolder holder, int position) {
        holder.radioButton.setText("It is button #" + position);
    }

    @Override
    public int getItemCount() {
        return 30;
    }

    // Use this method to get lastClickedItemPosition
    public int getLastClickedItemPosition() {
        return lastClickedItemPosition;
    }

    // This is inner class. From this class you can change 'lastClickedItemPosition' field of adapter
    class RadioViewHolder extends RecyclerView.ViewHolder {
        private RadioButton radioButton;

        public RadioViewHolder(@NonNull View itemView) {
            super(itemView);
            radioButton = (RadioButton) itemView;
            radioButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    lastClickedItemPosition = getAdapterPosition();
                }
            });
        }
    }
}

您可以致电adapter.getLastClickedItemPosition()获取上次单击的项目的位置。 MainActivty的完整代码在github上。 MainActivity是用Kotlin写的,但是不用担心,它很容易理解。

注意!!!

我不建议您在RadioButton中使用RecyclerViewRadioButton的常用用法是在RadioGroup内部。选中this link以了解有关RadioButton用法的更多详细信息。