Aditya Vyas - Lakhan Aditya Vyas - Lakhan - 4 months ago 12
Android Question

StaggaredGridLayoutManager not working properly

I am trying to change the view from Grid to list and list to Grid using

Recyclerview
. when i Run my app first i am getting view in grid manner like first image





enter image description here

Now when i click on icon to convert view from Grid to list i am getting it list manner like this

2.

enter image description here


  1. but now if i click on icon again to change view it will give proper output



enter image description here

Now issue is why i am not able to get view in grid manner as mentioned in 1 screenshot

oncreateview

gridimg.setOnClickListener(this);
llm = new LinearLayoutManager(ProductListActivity.this);
rv = (RecyclerView)findViewById(R.id.recycler_viewproduts);

rv.setLayoutManager(llm);


Getting Json response using volley and setting adapter

private void makeJsonArrayRequest() {



showpDialog();

JsonArrayRequest req = new JsonArrayRequest( url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
productlist = new ArrayList<ProductListModel>();
// Parsing json

ch_list = new ArrayList<String>();
color_list=new ArrayList<String>();

try {....................

rvAdapter = new RecyclerViewAdapter(ProductListActivity.this,productlist,ch_list);
rv.setAdapter(rvAdapter);

} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();

// notifying list adapter about data changes
// so that it renders the list view with updated data
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();

}
});


MyApplication.getInstance().addToReqQueue(req, "jreq");
}


onclick

case R.id.product_grid:

Toast.makeText(ProductListActivity.this, "Refresh App", Toast.LENGTH_LONG).show();
isViewWithCatalog = !isViewWithCatalog;
supportInvalidateOptionsMenu();
//loading = false;
rv.setLayoutManager(isViewWithCatalog ? new LinearLayoutManager(this) : new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
rv.setAdapter(rvAdapter);
break;

Answer

Change:

gridimg.setOnClickListener(this);
   llm = new LinearLayoutManager(ProductListActivity.this);
         rv = (RecyclerView)findViewById(R.id.recycler_viewproduts);

        rv.setLayoutManager(llm);

to

gridimg.setOnClickListener(this);
   llm =  new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
         rv = (RecyclerView)findViewById(R.id.recycler_viewproduts);

    rv.setLayoutManager(llm);
Comments