[Tex/LaTex] Uncover lstlisting on a particular slide using \onslide or \uncover

beamerlistingsoverlays

Updated:

How can I uncover a certain lstlisting environment on a particular slide using \onslide or \uncover?

For example:

\documentclass{beamer}
\usepackage{listings}

\begin{document}
\begin{frame}
  \onslide<1-> HI
  \onslide<2-> \begin{lstlisting} int i = 0; \end{lstlisting}
\end{frame}
\end{document}

Best Answer

Verbatim material cannot appear in an argument to another command (up to a certain point you could try using an external file and inputting it with \lstinputlisting) and use \uncover on \onslide, but the best approach here is to use the onlyenv environment for your listing (since the frame contains verbatim material it requires the fragile option):

\documentclass{beamer}
\usepackage{listings}

\begin{document}
\begin{frame}[fragile]
\begin{overlayarea}{\linewidth}{3cm}
  \onslide<1->{Hi}
  \begin{onlyenv}<2->
  \begin{lstlisting} 
  int i = 0; 
  \end{lstlisting}
  \end{onlyenv}
\end{overlayarea}  
\end{frame}
\end{document}

I also added an optional overlayarea environment to prevent possible "jumps". An animation of the result:

enter image description here