Adapter file:
public class CustomProductsAdapter extends BaseAdapter {
TextView textView;
ImageView imageView;
String[] title = new String[]{};
String[] image = new String[]{};
private LayoutInflater inflater = null;
public CustomProductsAdapter(Context context, String[] title, String[] image) {
this.title = title;
this.image = image;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return productList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_grid, null);
textView = (TextView) view.findViewById(R.id.textView);
imageView = (ImageView) view.findViewById(R.id.imageView);
return view;
}}
IN Activity initialize the gridview and set the Adapter Where title and images you need to send as List,Map,Array
GridView products= (GridView) view.findViewById(R.id.products_grid);
products.setAdapter(new CustomProductsAdapter(getContext(),title,image);
setDynamicHeight(products);
dynamic height method is here:
public void setDynamicHeight(GridView gridView) {
ListAdapter gridViewAdapter = gridView.getAdapter();
if (gridViewAdapter == null) {
return;
}
int totalHeight = 0;
int items = gridViewAdapter.getCount();
int rows = 0;
View listItem = gridViewAdapter.getView(0, null, gridView);
listItem.measure(0, 0);
totalHeight = listItem.getMeasuredHeight();
float x = 1;
if( items > 4 ){
x = items / 4;
if (x >= 2){
x = x-1;
}
rows = (int) (x + 1);
totalHeight *= rows;
}
ViewGroup.LayoutParams params = gridView.getLayoutParams();
params.height = totalHeight;
gridView.setLayoutParams(params);
}
Gridview in activity xml:
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/products_grid"
android:numColumns="4"
android:layout_marginTop="@dimen/margin_10"
android:layout_marginStart="@dimen/margin_8"
android:layout_marginEnd="@dimen/margin_14"
android:layout_marginBottom="@dimen/margin_24"
/>
Grid in Adapter file for injection
<ImageView
android:id="@+id/imageView"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="14dp"
android:layout_marginStart="24dp"
android:layout_marginBottom="5dp"
android:src="https://stackoverflow.com/questions/47153404/@mipmap/bus" />
<TextView
android:id="@+id/textView"
android:gravity="center"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginStart="5dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="14dp"
android:textSize="@dimen/textsize_12"
android:textColor="@color/mildblack"
android:text="Image Name" />
1
solved CustomGridView not working, not showing anything [closed]