1. While I was walking on the sidewalk, I was playing a game on my smartphone.

2. When I was walking on the sidewalk, I was playing a game on my smartphone.
(Is #2 grammatical?)

3. While I walked on the sidewalk, I played a game on my smartphone.

4. When I walked on the sidewalk, I played a game on my smartphone.
(Can we use both #3 and #4?)

Yes, they are all correct. The verb tenses match in both clauses in all four.

1. The first sentence, "While I was walking on the sidewalk, I was playing a game on my smartphone," is grammatically correct. It uses the past continuous tense ("was walking," "was playing") to describe two ongoing actions that happened simultaneously in the past. The verb "was playing" indicates that the action of playing the game was happening at the same time as the action of walking.

2. The second sentence, "When I was walking on the sidewalk, I was playing a game on my smartphone," is also grammatically correct. It follows the same structure as the first sentence and conveys the same meaning. The only difference is the use of "when" instead of "while," which does not affect the grammatical correctness.

3. The third sentence, "While I walked on the sidewalk, I played a game on my smartphone," is grammatically correct but expresses a different meaning. Unlike the first two sentences, which use the past continuous tense to describe simultaneous ongoing actions, this sentence uses the simple past tense ("walked," "played") to describe two separate actions that happened sequentially rather than concurrently.

4. The fourth sentence, "When I walked on the sidewalk, I played a game on my smartphone," is also grammatically correct. It has the same structure as the third sentence, using the simple past tense to describe separate actions. Again, the difference lies in the use of "when" instead of "while," which does not affect the grammatical correctness.

To summarize, all four sentences are grammatically correct, but they convey slightly different meanings. The first two sentences describe simultaneous actions, while the last two sentences describe separate actions. The choice between "while" and "when" depends on the specific context and the intended meaning of the sentence.