如何在 Android 的 RecyclerView 中添加项目符号列表?
Recycler View 允许我们显示项目列表,但是要将我们的列表转换为项目符号列表,我们必须做一些额外的工作。您可以按照下面给出的这些简单步骤来完成此任务:-
- 在依赖部分的 Recycler View 的build.gradle文件中添加支持库。
implementation 'androidx.recyclerview:recyclerview:1.1.0' - 在 drawable 文件夹中创建一个bullet.xml文件。
- 在activity_main.xml中,添加以下代码。
- 使用以下代码创建一个新的custom_layout.xml文件。
- 创建一个MyAdapter。 Java类并添加以下代码。
public class MyAdapter extends RecyclerView.Adapter
{ String text[]; Activity activity; public MyAdapter(Activity activity, String text[]) { this.activity = activity; this.text = text; } // This method is used to attach // custom layout to the recycler view @NonNull @Override public MyViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { View view = activity.getLayoutInflater() .inflate( R.layout.custom_layout, parent, false); return new MyViewHolder(view); } // This method is used to set the action // to the widgets of our custom layout. @Override public void onBindViewHolder( @NonNull MyViewHolder holder, int position) { holder.textView.setText(text[position]); } @Override public int getItemCount() { return text.length; } class MyViewHolder extends RecyclerView.ViewHolder { TextView textView; public MyViewHolder(@NonNull View itemView) { super(itemView); textView = itemView.findViewById(R.id.textView); } } } - 最后,在MainActivity 中。 Java添加以下代码。
public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; String text[] = { "Linear Search", "Binary Search", "Selection Sort", "Bubble Sort", "Insertion Sort", "Recursive Insertion Sort", "Merge Sort", "Iterative Merge Sort", "Quick Sort", "Heap Sort", "Counting Sort", "Klee’s Algorithm", "Karatsuba algorithm", "Dijkastra’s Shortest Path Algorithm", "Dial’s Algorithm", "Kruskal’s Minimum Spanning Tree", "Prim’s Minimum Spanning Tree", "Naive Pattern Searching", "KMP Algorithm", "Rabin-Karp Algorithm" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recycler_view); MyAdapter adapter = new MyAdapter(this, text); recyclerView.setLayoutManager( new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); } }
输出: