简体   繁体   中英

How can I create a variable that contain class to be used in intent

I have been searching through the webs for clues about a variable that can contain class object, and I found nothing. I believe there is some way to store an information about a class in a variable to be used in intent. Sorry for the bad explanation, here is the code to illustrate what I mean.

MainActivity.class

public class MainActivity extends Activity {

    Button startBtn, chooseLevelBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startBtn = (Button) findViewById(R.id.startBtn);
        chooseLevelBtn = (Button) findViewById(R.id.chooseLevelBtn);

        class classVariable = "Level001Activity.class";
        /*
         * I want a variable like this where I can store the Activity.class
         * So that I can use a function to determine the last level played,
         * and so when the player press playBtn, it would automatically
         * send the intent to the latest level
         * Now, how do I achieve this ?
         */

        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(),
                    classVariable);
                startActivity(i);
            }
        });
    }
}

PS I will be getting the last level played information from a json file I store inside the internal storage of the device. Or any better method is greatly appreciated. Thank you in advance.

Yes, you can do that. You need to make it Class rather than class and remove the quotes as it shouldn't be a String :

Class<? extends Activity> classVariable = Level001Activity.class;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM