Saturday, May 31, 2014

Android ArrayAdapter getView's "convertView" Parameter

The ListView and ArrayAdapter doesn't create a new View for every item in the list. Instead, view items are pooled and recycled as the user scrolls through the list. So what "getView" does is that sometimes it requires you to create a new View (when "convertView" is null) or to re-use an existing view (when "convertView" is not null).

Therefore, in getView, you should do a null check for convertView. If it is null, create a new View, otherwise, just reuse it.

Monday, May 26, 2014

Android Setting Layout Parameters Programmatically

This is how it's done:

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams();
params.setMargins(10, 0, 0, 0);

But the catch is, if you are adding these views programmatically in the first place, you will need to ensure that the above code runs only after the views have been added to the parent.

Android Design Resolution

If using "dp" i.e. density independent pixels, dp values specified in the app should be based on a 320x480 design resolution.

Sunday, May 25, 2014

Android Center Vertically in Parent

Instinctively, it's to use this, but sometimes it works, and sometimes it doesn't work:
android:layout_centerVertical="true"

When it doesn't work, try this:
android:layout_gravity="center_vertical"

Not sure why but that's just how it is.

Monday, May 12, 2014

AngularJS Two Way Data Binding Only Works One Way Error

There is a problem with two way data binding in AngularJS where the data binding only works one way. This happens when the HTML element bound to the data is inside an automatically created child scope (e.g. inside an ng-include or ng-repeat block).

Let's say the following code is within an ng-include block:


<input ng-model="valueX" />

If $scope.valueX is set as "100" in the controller, it will show "100" in the input box above. However, if the user updates the value, this value won't be reflected in "$scope.valueX", because in this case the child scope will create a copy of that, different from the parent scope value. This results in two way data binding only working one way.

One solution is to use objects rather than primitives e.g.

<input ng-model="anObject.valueX" />

But it does not work all the time. In the case it doesn't work, another option is to explicitly reference the $parent scope:

<input ng-model="$parent.anObject.valueX" />

Reference: https://github.com/angular/angular.js/wiki/Understanding-Scopes