0

Подскажите пожалуйста, как автоматически подгонять по высоте recyclerview_item, чтобы он был равен ширине колонки, в общем делать квадратным ? Сейчас ~ 180 dp установлено в макете..

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:padding="0dp"
android:layout_width="match_parent"
android:layout_height="180dp">

<TextView
    android:id="@+id/info_text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/obvodka"/>

</LinearLayout>

Колонки подгоняются под ширину экрана при повороте:

 //отследить поворот экрана
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if(recyclerView.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    } else if (recyclerView.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
    }

}

Адаптер:

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
Context contextActivity;


private String[] mData = new String[0];
private LayoutInflater mInflater;

// Data is passed into the constructor
public MyRecyclerViewAdapter(Context context, String[] data) {
    this.mInflater = LayoutInflater.from(context);
    this.mData = data;
    contextActivity = context;
}

// Inflates the cell layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);

    ViewHolder viewHolder = new ViewHolder(view);

    return viewHolder;
}

// Binds the data to the textview in each cell
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    String animal = mData[position];
    holder.myTextView.setText(animal);
}

// Total number of cells
@Override
public int getItemCount() {
    return mData.length;
}

// Stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView myTextView;

    public ViewHolder(View itemView) {
        super(itemView);
        myTextView = (TextView) itemView.findViewById(R.id.info_text);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        onItemClick(view, getAdapterPosition());
    }
}

// Convenience method for getting data at click position
public String getItem(int id) {
    return mData[id];
}

// Method that executes your code for the action received
public void onItemClick(View view, int position) {
   Toast.makeText(contextActivity, String.valueOf(position + 1),     0).show();
}
}

Добавил так:

// Stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView myTextView;
    public ViewHolder(final View itemView) {
        super(itemView);
        myTextView = (TextView) itemView.findViewById(R.id.info_text);
        itemView.setOnClickListener(this);
        if (itemView.getWidth() > 0) {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(itemView.getWidth(),itemView.getWidth());
            itemView.setLayoutParams(lp);
        } else {
            ViewTreeObserver vto = itemView.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                     itemView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(itemView.getWidth(),itemView.getWidth());
                    itemView.setLayoutParams(lp);
                }
            });
        }
    }
    @Override
    public void onClick(View view) {
        onItemClick(view, getAdapterPosition());
    }
}


Исправил макет:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:id="@+id/info_text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/obvodka"/>
</LinearLayout>

</LinearLayout>

Все равно ошибка !

4
  • можно попробовать fill_parent например
    – Andrew
    28 фев 2019 в 17:38
  • не, тогда во всю высоту экрана Item, надо как-то рассчитывать..
    – Alex455
    28 фев 2019 в 17:46
  • wrap_content я так понимаю тоже не подходит?
    – Andrew
    28 фев 2019 в 17:50
  • Не понимаю как задать высоту, равную ширине.. В адаптере типа того: @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.recyclerview_item, parent, false); view.setMinimumHeight(view.getWidth()); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; }
    – Alex455
    28 фев 2019 в 17:54

2 ответа 2

2

Попробуйте сделать в адаптере вот так (программно изменять высоту вью после отрисовки):

if (view.getWidth() > 0) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(view.getWidth(),view.getWidth());
        view.setLayoutParams(lp);
    } else {
        ViewTreeObserver vto = view.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(view.getWidth(),view.getWidth());
                view.setLayoutParams(lp);
            }
        });
}

А сам LinearLayout задать как wrap_content

7
  • Немножко вылетает с ошибкой.. Если убрать вторую часть условия, то не вылетает, но и не отрисовывает квадраты.. Не успевает правильно получить view.getWidth(), оно 0 равно.
    – Alex455
    28 фев 2019 в 18:16
  • вылетает потому, что вы применяете ко всему view (у которого нет родителя == LinearLayout). Добавьте в основной LL (который должен быть wrap_content по высоте) вью, с которым будете работать
    – Jarvis_J
    28 фев 2019 в 18:22
  • Добавил код адаптера в вопрос.. Не пойму куда добавить, у меня view.getWidth() = 0..
    – Alex455
    28 фев 2019 в 18:32
  • Добавьте во вьюхолдер и view замените на ваш itemView
    – Jarvis_J
    28 фев 2019 в 18:35
  • Я в вопросе написал, как исправил, все равно не получается.. Та же ошибка, и view.getWidth() = 0
    – Alex455
    28 фев 2019 в 18:47
1

Попробуйте такой layout. Код не нужен.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools">

    <TextView
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@drawable/obvodka"
        android:gravity="center"
        app:layout_constraintDimensionRatio="1:1"/>


</android.support.constraint.ConstraintLayout>

ЗЫ для androidx будет androidx.constraintlayout.widget.ConstraintLayout

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.