我有这个代码: public class Main扩展Activity {
GridView gridView;
static final String[] numbers = new String[] { "1", "2", "3", "4", "5",
"6", "7" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
gridView = (GridView) findViewById(R.id.grid1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),Activity1.class);
startActivity(i);
}
});
}
我希望当我点击1时转到activity1,当我点击2转到activity2等等。
甚至可能吗?
答案 0 :(得分:2)
是的可能
将您的活动名称放在String数组中
String[] values = new String[] { "Activity1", "Activtiy2", "Activity3" };
然后在onItemClick
String val = values[arg2]; // arg2 is the index of item
Class ourClass = Class.forName("yourpackagename."+val);
Intent intent = new Intent(ActivityName.this,ourClass);
startActivity(intent);
答案 1 :(得分:0)
感谢Raghunandan,我设法解决了这个问题:
String val = activities[arg2]; // arg2 is the index of item
Class ourClass = null;
try {
ourClass = Class.forName("com.example.challenge."+val);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(Day02.this,ourClass);
startActivity(intent);
}