BaseAdapter Example
In the example, animal images are displayed in the form of grids using a custom
adapter to show the usage of BaseAdapter.
Step 1: Ceate a new Android project called BaseAdapterExample.
Step 2: In the activity_main.xml (or) [Link] and add the following code that creates
the Gridview inside LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:footerDividersEnabled="false"
android:numColumns="3" />
</LinearLayout>
Step 3: In the Activity activity_gridview.xml add the following code inside the
Linearlayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitXY"
android:layout_margin="5dp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Step 3: In the [Link] and add the code below. The images of the animals
should be saved first in the drawable folder. The names that are used in the code must
be used or else use the names based on how you saved the images present in your
drawable folder.
package [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
GridView simpleGrid;
int animals[] = {[Link].animal13, [Link].animal14, [Link].animal15, R.
drawable.animal16, [Link].animal17, [Link].animal18, [Link].animal15,
[Link].animal16, [Link].animal17};
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
simpleGrid = (GridView) findViewById([Link]);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), animals);
[Link](customAdapter);
}
}
Step 4: Create a new class [Link] inside package and add the following
code
package [Link]; //Use your package
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class CustomAdapter extends BaseAdapter {
Context context;
int animals[];
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, int[] animals) {
[Link] = applicationContext;
[Link] = animals;
inflter = ([Link](applicationContext));
}
@Override
public int getCount() {
return [Link];
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = [Link]([Link].activity_gridview, null);
ImageView icon = (ImageView) [Link]([Link]);
[Link](animals[i]);
return view;
}
}
Output:
Execute the application and see how the animals are listed in Grids. So this is one use
of BaseAdapter in Gridview.