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
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015
Node.js / Express Programming Tip: Detect and Fix Memory LeaksOctober 27, 2015