I have a RecyclerView with a list of Cards. I want to know whether it's possible to change the RecyclerView's LayoutManager to Linear, when using a phone, and StaggeredGrid, when using a tablet, programmatically. My initial idea was to have the same code on the Activity, and only change the layout.xml, but given Android uses different LayoutManagers, it seems note complicated than that. I also tried using Cardslib library, but got reeeaally confused by the documentation, since there is no complete example with custom cards. Any ideas?
So, as I told @androholic, what I was trying to figure out is how to have the layout change depending on the devices format. This way, whenever the app was loaded on a tablet, a Grid was shown, and a List on phones. However, in order to do this with a RecyclerView, two LayouManagers would be needed: LinearLayoutManager for the list, and Staggered/GridLayoutManager, making the code a bit more complicated.
What I did: I used a GridLayoutManager for the general case. What I would change according to the screen size would be only the number of columns. This way, a list would be a RecyclerView with a GridLayoutManager with 1 column, and a grid would have more than one. In my case, I use only 2 columns.
My code is as follows.
public class AppListActivity extends AppCompatActivity {
private ArrayList<App> apps;
private int columns;
private String root = Environment.getExternalStorageDirectory().toString();
private boolean isTablet;
private RecyclerViewAdapter rvadapter;
public static Context context;
private SwipeRefreshLayout swipeContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
//CHECK WHETHER THE DEVICE IS A TABLET OR A PHONE
isTablet = getResources().getBoolean(R.bool.isTablet);
if (isTablet()) { //it's a tablet
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
columns = 2;
} else { //it's a phone, not a tablet
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
columns = 1;
}
//SwipeContainer SETUP
//ArrayList and RecyclerView initialization
apps = new ArrayList<App>();
RecyclerView rv = (RecyclerView) findViewById(R.id.recycler_view);
rv.setHasFixedSize(true);
GridLayoutManager gridlm = new GridLayoutManager(getApplicationContext(),columns);
rv.setLayoutManager(gridlm);
rvadapter = new RecyclerViewAdapter(apps);
rv.setAdapter(rvadapter);
}
public boolean isTablet() {
return isTablet;
}
The method isTablet is pretty much the same one on @androholic's answer. Hopefully, this will clear up any doubts on what my question was (I realize my wording wasn't the best), and what I accomplished.