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
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021
Vault (Desktop) Version 0.72 ReleasedOctober 6, 2021
EBT Compass is Now Available for Android DevicesJune 2, 2021