The 31-year-old scored a 65-ball 75 studded with four boundaries and three sixes to lift his team from a precarious 120-7 to 200 in 49.3 overs as Sri Lankan bowlers put Pakistan in trouble after they won the toss and batted.
Afridi played against his style of trying to hit every ball out of the ground and added an invaluable 61 runs for the eighth wicket with tail-ender Saeed Ajmal who finished with 20.
The swashbuckling Afridi hit spinner Seekkugge Prassana over extra cover for a six to reach his 31st half-century --his first in 15 innings -- before hitting the same bowler for two boundaries and a six to take 19 in the 43rd over.
He finally fell, caught behind off paceman Thissara Perera, in the next over.
Sri Lanka, aiming to level the series after losing the first and third matches in Dubai, had kept Pakistan in check before Afridi's knock.
Paceman Dilhara Fernando (3-26) provided the early breakthrough when he had Imran Farhat caught behind for 10 with his first delivery of the match and then returned for his second spell to remove Younis Khan (18).
When Mohammad Hafeez (27) fell caught at long-leg off a miscued sweep Pakistan lost four wickets in the space of just 14 runs.
Leg-spinner Jeevan Mendis then trapped Shoaib Malik and Umar Akmal (both made two) in successive overs to leave Pakistan struggling at 71-5.
Afridi and Misbah-ul Haq added 26 for the sixth wicket before the Pakistan captain fell to a silly run out.
Pakistan brought in paceman Aizaz Cheema and Malik in place of Sohail Tanvir and Abdul Razzaq from Monday's line-up, but Sri Lanka kept an unchanged combination.