如何在Android Studio的RecyclerView中对名称进行字母排序

huangapple go评论74阅读模式
英文:

How to apply alphabetical sorting for names in a Recylcerview in android studios

问题

I have a student tracking app that uses firebase for the backend. What I want to do now is to be able to sort the students by name once the Order Students button has been clicked. Right now I have a method that will sort the student by name using a Comparator attached to the button. I verified that it actually sorts by attaching println statements after the sorting is done. Now I am trying to figure out how to apply this logic to the RecyclerView in which the image of the student and names are being displayed.

activity_view_students.xml

<!-- ... (Layout code) ... -->

ViewStudents.class

public class ViewStudents extends AppCompatActivity {
    // ... (Other code) ...

    private void GetDataFromFirebase() {
        // ... (Firebase data retrieval code) ...
    }

    private void ClearAll() {
        // ... (Clear data code) ...
    }

    public void orderStudents(View view) {
        // ... (Order students code) ...
    }
}

RecycleAdapter.class

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    // ... (Other code) ...

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // ... (Bind data to views code) ...
    }

    // ... (Other code) ...
}

Note: I have omitted the detailed code within each section since you requested only the translated parts. If you have any specific questions or need further assistance with the code, please feel free to ask.

英文:

I have a student tracking app that uses firebase for the backend. What I want to do now is to be able to sort the students by name once the Order Students button has been clicked. Right now I have a method that will sort the student by name using a Comparator attached to the button. I verified that it actually sorts by attaching println statements after the sorting is done. Now I am trying to figure out how to apply this logic to the RecyclerView in which the image of the student and names are being displayed. I will post the relevant code down below. Thank you all.

So the flow would look like this

Order Students Button Clicked -&gt; Students are ordered by Alphabetical Order based on Name in RecyclerView

Edit
I have posted the code for the RecyclerAdapter class below.

activity_view_students.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.ViewStudents&quot;&gt;

    &lt;Button
        android:id=&quot;@+id/addStudentButton&quot;
        android:layout_width=&quot;50dp&quot;
        android:layout_height=&quot;50dp&quot;
        android:text=&quot;Add a Student&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

    &lt;androidx.recyclerview.widget.RecyclerView
        android:id=&quot;@+id/recyclerView&quot;
        android:layout_width=&quot;409dp&quot;
        android:layout_height=&quot;729dp&quot;
        android:layout_marginEnd=&quot;1dp&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; &gt;

    &lt;/androidx.recyclerview.widget.RecyclerView&gt;

    &lt;Button
        android:id=&quot;@+id/orderStudents&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:onClick=&quot;orderStudents&quot;
        android:text=&quot;Order Students&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

ViewStudents.class

public class ViewStudents extends AppCompatActivity {


    RecyclerView recyclerView;
    Button addStudent;


    private DatabaseReference myRef;

    public ArrayList&lt;Students&gt; students;
    private RecyclerAdapter recyclerAdapter;
    private Button orderStudents;

    private EditText mEditTextAge;
    private EditText mEditTextAssignment;

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

        recyclerView = findViewById(R.id.recyclerView);
        addStudent = findViewById(R.id.addStudentButton);
        mEditTextAge = findViewById(R.id.EditTextAge);
        mEditTextAssignment = findViewById(R.id.EditTextAssignment);
        orderStudents = findViewById(R.id.orderStudents);

        addStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ViewStudents.this, AddStudent.class));
            }
        });

        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.setHasFixedSize(true);

        myRef = FirebaseDatabase.getInstance().getReference();

        students = new ArrayList&lt;&gt;();

        ClearAll();

        GetDataFromFirebase();



    }
   // This method will make a call to firebase and get names and 
   // images of the students in the db
    private void GetDataFromFirebase() {
        Query query = myRef.child(&quot;student&quot;);

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                ClearAll();
                for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    Students student = new Students();
                    if (snapshot.child(&quot;url&quot;).getValue() == null) {
                        student.setImageUrl(snapshot.child(&quot;imageUrl&quot;).getValue().toString());
                    }
                    else {
                        student.setImageUrl(snapshot.child(&quot;url&quot;).getValue().toString());

                    }
//                    student.setAge(mEditTextAge.getText().toString());
//                    student.setAssignment(mEditTextAssignment.getText().toString().trim());
                    student.setName(snapshot.child(&quot;name&quot;).getValue().toString());
                    students.add(student);
                }
                recyclerAdapter = new RecyclerAdapter(getApplicationContext(), students);
                recyclerView.setAdapter(recyclerAdapter);
                recyclerAdapter.notifyDataSetChanged();
            }

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

            }
        });
    }
    // will clear any pre-existing data 
    private void ClearAll() {
        if (students != null) {
            students.clear();

            if(recyclerAdapter != null) {
                recyclerAdapter.notifyDataSetChanged();
            }
        }
        students = new ArrayList&lt;&gt;();
    }

   // method to order students by name
    public void orderStudents(View view) {
        Intent orderIntent = new Intent(this, ViewStudents.class);
        startActivity(orderIntent);
        orderStudents.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collections.sort(students, new Comparator&lt;Students&gt;() {
                    @Override
                    public int compare(Students o1, Students o2) {
                        return o1.name.compareTo(o2.name);
                    }
                });
            }
        });

        for(int i = 0; i &lt; students.size(); i++){
            System.out.println(&quot;Students ==&gt; &quot; + students.get(i).getName());
        }

    }

RecycleAdapter.class

package com.example.studenttracker;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

public class RecyclerAdapter extends RecyclerView.Adapter&lt;RecyclerAdapter.ViewHolder&gt; {
    private OnItemClickListener mListener;
    public interface OnItemClickListener {
        void onItemClick(int position);
    }
    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }
    private static final String Tag = &quot;RecyclerView&quot;;
    private Context mContext;
    private ArrayList&lt;Students&gt; studentsArrayList;

    public RecyclerAdapter(Context mContext, ArrayList&lt;Students&gt; studentsArrayList) {
        this.mContext = mContext;
        this.studentsArrayList = studentsArrayList;
    }

    @NonNull
    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.student_item,parent,false);
        return new ViewHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //TextView
        holder.textView.setText(studentsArrayList.get(position).getName());

        Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);

    }

    @Override
    public int getItemCount() {
        return studentsArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.imageView);
            textView = itemView.findViewById(R.id.textView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        int position = getAdapterPosition();
                        
                    }
                }
            });
        }
    }
}

答案1

得分: 2

将您的 RecyclerAdapter 修改为扩展 ListAdapter,然后您可以让 orderStudents 点击方法修改适配器中的列表,例如:

// 按姓名对学生进行排序的方法
public void orderStudents(View view) {
    Intent orderIntent = new Intent(this, ViewStudents.class);
    startActivity(orderIntent);
    orderStudents.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            List<Students> l = recyclerAdapter.getCurrentList();
            Collections.sort(l, new Comparator<Students>() {
                @Override
                public int compare(Students o1, Students o2) {
                    return o1.name.compareTo(o2.name);
                }
            });
            recyclerAdapter.submitList( l );
        }
    });
}
英文:

Change your RecyclerAdapter to extend ListAdapter, then you can have your orderStudents click method modify the list in the adapter, for example:

// method to order students by name
public void orderStudents(View view) {
    Intent orderIntent = new Intent(this, ViewStudents.class);
    startActivity(orderIntent);
    orderStudents.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            List&lt;Students&gt; l = recyclerAdapter.getCurrentList();
            Collections.sort(l, new Comparator&lt;Students&gt;() {
                @Override
                public int compare(Students o1, Students o2) {
                    return o1.name.compareTo(o2.name);
                }
            });
            recyclerAdapter.submitList( l );
        }
    });

huangapple
  • 本文由 发表于 2020年7月27日 00:44:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63102993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定