Android TableLayout - How to dynamically determine cells per row? -


i need create tablelayout view can dynamically add columns based upon size of screen.

for example, if on phone, maximum number of cells can add per row 5. however, if on tablet, maximum number of cells can add per row 10.

the 5 , 10 values magic numbers.

ideally, query device determine size of screen, , adjust number of columns based upon size.

here code creating tablelayout (it works fine):

 tablelayout tablelayout = new tablelayout(mcontext);     tablelayout.setlayoutparams(new tablelayout.layoutparams(tablelayout.layoutparams.match_parent,             tablelayout.layoutparams.wrap_content));      tablerow row = new tablerow(mcontext);     row.setlayoutparams(new tablerow.layoutparams(tablerow.layoutparams.match_parent,             tablerow.layoutparams.wrap_content));      string[] separated = scheduletimes.split(",");     (int s = 0; s < separated.length; s++) {          // 5 per row         if ((s % itemsperrow) == 0) {             tablelayout.addview(row);              row = new tablerow(mcontext);             row.setlayoutparams(new tablerow.layoutparams(tablerow.layoutparams.match_parent,                     tablerow.layoutparams.wrap_content));         }          textview tv = new textview(mcontext);         tv.setlayoutparams(new tablerow.layoutparams(tablerow.layoutparams.wrap_content,                 tablerow.layoutparams.wrap_content));         tv.setpadding(5, 5, 5, 5);         tv.setgravity(gravity.right);         tv.settypeface(typefacesingleton.getrobotoregular());         tv.settextsize(16);         tv.settext(separated[s].trim());          row.addview(tv);     }      tablelayout.addview(row); 

any thoughts on how can determine number of cells can add per row (i.e., set itemsperrow)?

get display width in dp , figure out how many dps want per cell. think you've done hard work already.

 displaymetrics displaymetrics = context.getresources().getdisplaymetrics();  float dpwidth = displaymetrics.widthpixels / displaymetrics.density;   itemsperrow = dpwidth / cellwidthdp; 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -