尝试这个
活动代码
public class TestActivity extends AppCompatActivity { RecyclerView recyclerView; ArrayListarrayList = new ArrayList<>(); FlexboxAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); recyclerView = findViewById(R.id.recyclerView); initArray(); FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this); layoutManager.setFlexDirection(FlexDirection.ROW); layoutManager.setJustifyContent(JustifyContent.CENTER); layoutManager.setAlignItems(AlignItems.CENTER); recyclerView.setLayoutManager(layoutManager); adapter = new FlexboxAdapter(this, arrayList); recyclerView.setAdapter(adapter); } private void initArray() { arrayList.add("Nileshfgfdgfdgfdggfgfgfdgvcb"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nileshfgfdgfdgfdggfgcvbcvb"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nileshfgfdgfdgfdggfgfdgdfgcvb"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nileshfgfdgfdgfdggfgcvb"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nileshfgfdgfdgfdggfgdfgdfgcvb"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); arrayList.add("Nileshfgfdgfdgfdggfgdfgcvb"); arrayList.add("Nilesh"); arrayList.add("Nilesh"); } }
适配器代码
public class FlexboxAdapter extends RecyclerView.Adapter{ Context context; ArrayListarrayList = new ArrayList<>(); public FlexboxAdapter(Context context, ArrayListarrayList) { this.context = context; this.arrayList = arrayList; } @Override public FlexboxAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.custom_layout, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(FlexboxAdapter.ViewHolder holder, int position) { holder.title.setText(arrayList.get(position)); } @Override public int getItemCount() { return arrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView title; public ViewHolder(View itemView) { super(itemView); title = itemView.findViewById(R.id.tvTitle); } } }
定制布局
活动布局
OUTPUT