如何在 Android Studio 中更改方向更改时更改网格布局中的列跨度?

How to change the column span in grid layout on orientation change in Android Studio?

我有一个 2 列的网格布局,但我想在方向更改为横向时将其更改为 3 列。我该怎么做?

这是我设置 RecyclerView 和网格的 OnCreate 方法。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        birdList = new ArrayList<>();
        getJSONfromFile();

        // Recycler View
        mainRecyclerView = findViewById(R.id.main_recycler_view);
        mainRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));

        // Set Adapter
        BirdAdapter adapter = new BirdAdapter(this, birdList);
        mainRecyclerView.setAdapter(adapter);
    }

尝试在您的 onCreateView 方法中处理它,因为每次方向改变时都会调用它:

if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
     mainRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
}
else{
     mainRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
}