В моем фрагменте я'м сидит мой GridLayout следующим образом:
mRecycler.setLayoutManager(новый GridLayoutManager(rootView.метода getcontext(), 2));
Итак, я просто хочу это изменить 2
на 4
, когда пользователь поворачивает телефон/планшет. Я'ве читать про onConfigurationChanged
и я пытался заставить его работать для моего случая, но это вовсе'т иду в правильном направлении. Когда я повернуть мой телефон, приложение падает...
Не могли бы вы сказать мне, как решить эту проблему?
Вот мой подход, чтобы найти решение, которое работает неправильно:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
}
}
Заранее спасибо!
Если у вас есть более чем одно условие или значение в несколько мест, это может перейти из рук довольно быстро. Я предлагаю создать следующую структуру:
res
- values
- dimens.xml
- values-land
- dimens.xml
с res/values/dimens.xml быть:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="gallery_columns">2</integer>
</resources>
и res/values-land/dimens.xml быть:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="gallery_columns">4</integer>
</resources>
И тогда код становится (и навсегда остается) такой:
final int columns = getResources().getInteger(R.integer.gallery_columns);
mRecycler.setLayoutManager(new GridLayoutManager(mContext, columns));
Вы можете легко увидеть, как легко это, чтобы добавить новые способы определения количества столбцов, например, используя -w500dp
/-w600dp
/-w700dp ресурсные папки вместо
земля`.
Это's также довольно легко сгруппировать эти папки в отдельную папку ресурсов в случае, если вы не'т хотите загромождать другие (более актуально) ресурсов:
android {
sourceSets.main.res.srcDir 'src/main/res-overrides' // add alongside src/main/res
}
То в вашем методе onCreateView, поскольку в нем будет вызываться каждый раз, когда там'с изменением ориентации:
if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
}
else{
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
}
Просмотр корзины поддерживает AutofitRecycleView.
Вы должны добавить андроид:numColumns="и auto_fit"
В В вашего XML-файла.
Вы можете обратиться к этой AutofitRecycleViewLink
Более надежный способ определения нет. столбцов будет рассчитать в зависимости от ширины экрана и во время выполнения. Я обычно использую следующую функцию для этого.
public static int calculateNoOfColumns(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
int scalingFactor = 200; // You can vary the value held by the scalingFactor
// variable. The smaller it is the more no. of columns you can display, and the
// larger the value the less no. of columns will be calculated. It is the scaling
// factor to tweak to your needs.
int columnCount = (int) (dpWidth / scalingFactor);
return (columnCount>=2?columnCount:2); // if column no. is less than 2, we still display 2 columns
}
Это более динамичный способ для точного расчета нет. из колонны. Это будет более адаптивной для пользователей различные размеры экрана без д только двух возможных значений.
Примечание: Вы можете изменять значение проведенного scalingFactor переменной. Чем меньше это больше нет. из колонки вы можете отобразить, и чем больше значение, тем меньше нет. столбцов будет рассчитываться. Это коэффициент масштабирования настроить для ваших нужд.
В методе onCreate (событие) можно использовать StaggeredGridLayoutManager
mRecyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(
1, //number of grid columns
GridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mStaggeredGridLayoutManager);
Затем, когда пользователь вращает захват экрана случае, и автоматически меняется количество столбцов
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
mStaggeredGridLayoutManager.setSpanCount(1);
} else {
//show in two columns
mStaggeredGridLayoutManager.setSpanCount(2);
}
}
Я закончил обработку этого в методе onCreate.
private RecyclerView recyclerView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
Configuration orientation = new Configuration();
if(this.recyclerView.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else if (this.recyclerView.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
}
connectGetApiData();
}
Он работал отлично для моего приложения.
Вы можете реализовать метод в onMeasure recyclerView. Во-первых, создать класс java AutofitRecyclerView
public class AutofitRecyclerView extends RecyclerView {
//private GridLayoutManager manager;
private StaggeredGridLayoutManager manager;
private int columnWidth = -1;
public AutofitRecyclerView(Context context) {
super(context);
init(context, null);
}
public AutofitRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public AutofitRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
if (attrs != null) {
int[] attrsArray = {
android.R.attr.columnWidth
};
TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
columnWidth = array.getDimensionPixelSize(0, -1);
array.recycle();
}
manager = new StaggeredGridLayoutManager(1, GridLayoutManager.VERTICAL);
setLayoutManager(manager);
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(widthSpec, heightSpec);
if (columnWidth > 0) {
int spanCount = Math.max(1, getMeasuredWidth() / columnWidth);
manager.setSpanCount(spanCount);
}
}}
В файле макета в XLM activity_main.xml
<yourpackagename.AutofitRecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="@dimen/column_width"
android:clipToPadding="false"/>
Затем установите переменную ширину каждого элемента в размер файла значения папку values/dimens.xml
<resources>
<dimen name="column_width">250dp</dimen>
</resources>
Он может быть для разных разрешений экрана values-xxhdpi/dimens.xml
<resources>
<dimen name="column_width">280dp</dimen>
</resources>
В вашей деятельности в событие onCreate поместите следующий код
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.addItemDecoration(new MarginDecoration(this));
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(new NumberedAdapter(50));
}