I am loading gridview dynamically with buttons. So for that I am using scrollview, But if i assign wrap_content as height to gridview all the buttons are not displayed. I do
try this
int totalHeight = (count / <number of items in a row>);
if (count % <number of items in a row> != 0) {
totalHeight++;
}
ViewGroup.LayoutParams params = gridview.getLayoutParams();
params.height = <height of a row> * totalHeight;
gridview.setLayoutParams(params);
gridview.requestLayout();
You need to create a new class for example
public class WrappingGridView extends GridView {
public WrappingGridView(Context context) {
super(context);
}
public WrappingGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WrappingGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSpec = heightMeasureSpec;
if (getLayoutParams().height == LayoutParams.WRAP_CONTENT) {
// The great Android "hackatlon", the love, the magic.
// The two leftmost bits in the height measure spec have
// a special meaning, hence we can't use them to describe height.
heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightSpec);
}
}
also you need to change in your XML
<com.your.project.WrappingGridView
android:id="@+id/gridviewtable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:verticalSpacing="10dp"/>
and finally in your java class you need to chance the object GridView to WrappingGridView
This or something similar should do it. (code as i remember it)
myImageView.setLayoutParams(new ImageView.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, (LinearLayout.LayoutParams.WRAP_CONTENT));
android:layout_height="wrap_content"
cannot be used for subclasses of AdapterView
(e.g. ListView and GridView). The GridView would have to get each row's height in order to calculate its own height.
Remove the ScrollView
and the LinearLayout
, you don't need them. The GridView already has its own scrolling logic built-in.
This is a Frankenstein of many answers before me but it is the only thing has worked for me so far:
private static void resizeGridView(GridView gridView, int rows) {
int measuredHeight = gridView.getMeasuredHeight();
ViewGroup.LayoutParams params = gridView.getLayoutParams();
params.height = measuredHeight * rows;
gridView.setLayoutParams(params);
gridView.requestLayout();
}
Call this after you've updated the content to be displayed to the gridView.