Центрирование элементов RecyclerView с помощью FlexboxLayoutManager - PullRequest
0 голосов
/ 15 мая 2018

Как мне центрировать все мои RecyclerView элементы, используя FlexboxLayoutManager?Мне нужно, чтобы элементы были центрированы так:

Correctly centered items

Я пытался безуспешно: My attempt, incorrect

Мой код, в котором я установил менеджер раскладки:

val layoutManager = FlexboxLayoutManager(this)
        layoutManager.setFlexWrap(FlexWrap.WRAP)
        layoutManager.setFlexDirection(FlexDirection.ROW)
        layoutManager.setJustifyContent(JustifyContent.FLEX_START)
        layoutManager.setAlignItems(AlignItems.FLEX_START)

        val adapter = TagAdapter(tags)
        tagRecyclerView.adapter = adapter
        tagRecyclerView.layoutManager = layoutManager

(я пытался установить layoutManager.setAlignItems(AlignItems.FLEX_START) на layoutManager.setAlignItems(AlignItems.CENTER), однако он не работал ...

Ответы [ 2 ]

0 голосов
/ 24 мая 2018

Краткий ответ

Вы используете layoutManager.setAlignItems(AlignItems.FLEX_START).Это вызывает начальное выравнивание.

Вы должны использовать одно из двух выравниваний, которое соответствует вашим требованиям.

layoutManager.setAlignItems(AlignItems.CENTER).

или

layoutManager.setAlignItems(AlignItems.SPACE_AROUND).

Примечание:

Потому что вы сказали это

@ MarcEstrada да, не работает

Сохраняйте ширину макета элемента wrap_content.(все дочерние элементы с родителями должны иметь wrap_content ширину.) как android:layout_width="wrap_content"

Если вы используете match_parent ширину, вы не получите центрированные элементы.

0 голосов
/ 18 мая 2018

Попробуйте это

КОД ДЕЯТЕЛЬНОСТИ

public class TestActivity extends AppCompatActivity {


    RecyclerView recyclerView;
    ArrayList<String> arrayList = 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<FlexboxAdapter.ViewHolder> {

    Context context;
    ArrayList<String> arrayList = new ArrayList<>();

    public FlexboxAdapter(Context context, ArrayList<String> arrayList) {
        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);
        }
    }
}

ТАМОЖЕННЫЙ ПЛАН

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center">


    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:padding="5dp"
        android:text="Nilesh"
        android:textColor="#000"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>

ПЛАН РАБОТЫ

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".TestActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


</LinearLayout>

OUTPUT

enter image description here

...