So what do we do when we have an adapter being bound to a ListView but we want to change something with a field prior to display? We use a TransformationMethod. In this case, our adapter is ActiveAndroid’s EntityAdapter.

P.S. I’ve just created a new view for simplicity’s sake, but you should always be re-using views. See Romain Guy’s Google IO presentation for details.

public class CustomViewAdapter extends EntityAdapter
{
	public CustomViewAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
	{
		super(context, data, resource, from, to);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View v = super.getView(position, convertView, parent);
		TextView date = (TextView) v.findViewById(R.id.date);
		date.setTransformationMethod(new DateTransformationMethod());

		return v;
	}

	private class DateTransformationMethod implements TransformationMethod
	{
		@Override
		public CharSequence getTransformation(CharSequence text, View view)
		{
			String result = "";

			if (!text.toString().equals(new SimpleDateFormat("yyyy/MM/dd").format(new Date(0))))
			{
				try
				{
					result = DateUtils.getRelativeTimeSpanString(
						new SimpleDateFormat("yyyy/MM/dd").parse(text.toString()).getTime(),
						new Date().getTime(),
						DateUtils.DAY_IN_MILLIS,
						DateUtils.FORMAT_ABBREV_RELATIVE)
					.toString();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			// the output isn't quite what we're after, so let's modify it slightly
			if (result.equals(""))
			{
				result = "N/A";
			}
			else if (result.equals("0 days ago"))
			{
				result = "Today";
			}
			else if (result.equals("yesterday"))
			{
				result = "Yesterday";
			}

			return result;
		}

		@Override
		public void onFocusChanged(View arg0, CharSequence arg1, boolean arg2, int arg3, Rect arg4)
		{
			// unimplemented
			// worth noting that TransformationMethods are usually used for password fields etc,
			// so on loss of focus you'd blur the last remaining letter, for example
			// this is the function you'd use to trigger it
		}

	}
}
Advertisements