They are done magnetically. The fabric has metallic properties that they wear. Even though the uniforms are not actually metallic. They "resemble" it as far as the physics of the com badges are concerned.
In the Star Fleet Technical Manual (1973), it was referred to as "magnatomic adhesion"
And in the DS9 episode where Worf appeared, a metal strip on the side of the collar is seen (on the inside of where the pips go on the outside). Presumably something similar for the combadges? Although I have no clue how they seem to be able to stick onto any clothing. Probably best not to think about it (after all, it's just velcro in real life)
Kitface 11:19, June 14, 2011 (UTC)
In 1 of the TNG films, I think it was Insurection-- Picard is seen removing the four indivdual pips for a Starfleet captain from his uniform tunic. Although this doesn't disprove the magnatomic adhesion explanation above.