Eric Bergman-Terrell's Blog

Android Programming Tip: Recycle Views in Adapters
December 7, 2012

My new EBTCalc programmable calculator app has various Adapters used to populate databound Views. For instance, I use a BaseAdapter subclass to populate a GridView with the custom buttons found in the Javascript code.

Inflating a View, in other words creating a View from an XML layout file, is expensive. For this reason, Android will sometimes allow you to recycle a no-longer-used View in your Adapter.getView method. If your Adapter's getView method's View argument is non-null, use that View rather than creating a new View by calling LayoutInflater.inflate. When your getView is passed a non-null view, you'll still need to initialize the values of any Views inside of the View, but you will not need to inflate the View.

...

	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		// If convertView is not null, we recycle it (but repopulate it). If it's null we inflate a new view and populate it.
		View gridView = (convertView == null) ? inflater.inflate(R.layout.programmable_button, null) : convertView;

		// set value into button.
		Button programmableButton = (Button) gridView.findViewById(R.id.ProgrammableButton);
		
		MethodMetadata methodMetadata = (MethodMetadata) getItem(position);
		
		String argumentList = (methodMetadata.getArguments().size() > 0 && !methodMetadata.isButtonTextCustom()) ? String.format("(%s)", methodMetadata.getArgumentList()) : "";
		
		programmableButton.setText(String.format("%s%s", methodMetadata.getButtonText(), argumentList));

...
Keywords: Android, View, Inflate, getView, Adapter, LayoutInflater, performance, layout

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
Node.js + Express: How to Block Requests by User-Agent HeadersJanuary 7, 2026
Vault 3 is Now Available for Windows on ARM Machines!December 13, 2025
Vault 3: How to Include Outline Text in Exported PhotosOctober 26, 2025
.NET Public-Key (Asymmetric) Cryptography DemoJuly 20, 2025
Raspberry Pi 3B+ Photo FrameJune 17, 2025
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023