I am living in China now, but will be leaving soon. I want to apply for a Sri Lankan visa while I'm here in China. If it is granted, can I still use the visa after I leave China and return to my own country, Ghana?
A visa is typically about entry to the issuing country, not about making a specific journey.
There may be exceptions, but usually one applies for a visa in the country of residence at the time of the application. You may be asked to prove you are in that country legally.
Many travelers enter a country from a different country from the one they were living in at the time the visa was issued. For example, consider a tourist who may visit several countries within a couple of weeks. They will normally obtain all required visas in advance, from their country of residence.
Yes. Visas are not typically issued to you solely because of where you live (although it sometimes plays a small part) but because you qualify according to a bunch of criteria set by the embassy. I previously lived in Ghana and acquired visas I continued to use after moving to the USA.
Changing your residence or nationality usually does not invalidate the visa except in extreme cases like acquiring Israeli citizenship at which point some Arab countries will ban you and invalidate your prior visa based on their policy as part of the Arab League boycott of Israel.
Note however that conversely, if for example you have a ban from a particular country, changing your nationality does not change your ban. See UK: Is a 10 year ban still valid after acquiring new citizenship?
PS: The answer assumes you are in China legally