WASHINGTON — Justice Anthony M. Kennedy announced on Wednesday that he would retire this summer, setting in motion a furious fight over the future of the Supreme Court and giving President Trump the chance to put a conservative stamp on the American legal system for generations.

Justice Kennedy, 81, has been a critical swing vote on the sharply polarized court for nearly three decades as he embraced liberal views on gay rights, abortion and the death penalty but helped conservatives trim voting rights, block gun control measures and unleash campaign spending by corporations.

His replacement by a conservative justice — something Mr. Trump has vowed to his supporters — could imperil a variety of landmark Supreme Court precedents on social issues where Justice Kennedy frequently sided with his liberal colleagues, particularly on abortion.

Mr. Trump and his Republican allies have hoped for months that Justice Kennedy might retire, clearing a way for a new, more conservative jurist before Democrats had an opportunity to capture the Senate and block future Republican nominees. In contrast to his frequent criticisms of Chief Justice John G. Roberts Jr., a generally reliable conservative, Mr. Trump has frequently heaped praise on Justice Kennedy and even has suggested that he might nominate one of his former clerks to the bench — subtle nudges the president hoped would make Justice Kennedy more comfortable with the idea of stepping down.