简体   繁体   中英

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

I have a 2 column grid layout but I would like to change it to 3 columns when the orientation changes to landscape. How do I go about doing so?

Here is my OnCreate method where I set up the RecyclerView and Grid.

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

Try handling this inside your onCreateView method instead since it will be called each time there's an orientation change:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM