8. 利用反射机制, ListArray,intent来实现多Activity的切换
package com.example.thenewboston; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class Menu extends ListActivity{
//classes里面存放的都是其他Activity的name private String classes[] = {"MainActivity", "Splash", "example2", "example3", "example4", "example5"}; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //利用ListAdapter将classes与onListItemClick()关联 setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes)); }
@Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id);
//每当click的时候可以得到所click的Activity name在Array中的position String cheese = classes[position]; try {
//利用反射找到Class类 Class ourClass = Class.forName("com.example.thenewboston."+cheese);
//将这个class传递给Intent Intent intent = new Intent(Menu.this, ourClass);
//start activity startActivity(intent); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } } }