Development Tip

GridLayoutManager 및 RecyclerView로 열 수 변경

yourdevel 2021. 1. 9. 11:01
반응형

GridLayoutManager 및 RecyclerView로 열 수 변경


내 조각 내에서 다음과 같은 방식으로 GridLayout을 설정하고 있습니다. mRecycler.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));

그래서, 난 그냥를 변경하려면 2A의 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));
        }
    }

미리 감사드립니다!


방향이 변경 될 때마다 호출되므로 대신 onCreateView 메서드 내에서 처리해보십시오.

if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
     mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
}
else{
     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대신 자원 폴더를 -land.

다른 (관련성이 더 높은) 리소스를 복잡하게 만들고 싶지 않은 경우 이러한 폴더를 별도의 리소스 폴더로 그룹화하는 것도 매우 쉽습니다.

android {
    sourceSets.main.res.srcDir 'src/main/res-overrides' // add alongside src/main/res
}

Recycle View는 AutofitRecycleView를 지원합니다.

android: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
}

It is a more dynamic method to accurately calculate the no. of columns. This will be more adaptive for users of varying screen sizes without being resticted to only two possible values.

NB: 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.


In the onCreate () event you can use StaggeredGridLayoutManager

mRecyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);      

mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(
       1, //number of grid columns
       GridLayoutManager.VERTICAL);      

mRecyclerView.setLayoutManager(mStaggeredGridLayoutManager);

Then when the user rotates the screen capture the event, and change the number of columns automatically

@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);           
    }
}

I ended up handling this in the onCreate method.

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();
}

It worked out perfectly for my app.


You can implement the method in your recyclerView onMeasure. First, create the java class 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);
    }
}}

In your xlm layout file 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"/>

Then set the variable to the width of each item in the file size of the values folder values/dimens.xml

<resources>
  <dimen name="column_width">250dp</dimen>
</resources>

It can be for different screen resolutions values-xxhdpi/dimens.xml

<resources>
 <dimen name="column_width">280dp</dimen>
</resources>

In your activity in the onCreate event place the following code

@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));
}

ReferenceURL : https://stackoverflow.com/questions/29579811/changing-number-of-columns-with-gridlayoutmanager-and-recyclerview

반응형