嘿我尝试使用String变量从这个开始一个新活动,但每次我这样做都没有任何反应。我假设程序只是抛出Class not found异常。 Class.forName行有问题。请查看我的代码和帮助。我创建的唯一活动是StartingPoint活动,我知道的示例活动不会起作用,但是当我选择StartingPoint时它甚至都不起作用。当我将意图线更改为" ...新意图(MenuActivity.this,Starting point.class)"它仍然无法正常工作,所以我假设它已经在Class.forName()行中抛出了异常,因为当我把那个Intent(MenuActivity.this,Starting point.class)"在try块之外它可以工作!!!
package com.example.music;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MenuActivity extends ListActivity {
String[] classes = { "StartingPoint", "example1","example2", "example3",
"example4", "example5", "example6"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(MenuActivity.this,
android.R.layout.simple_list_item_1, classes));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try{
Class<?> ourClass = Class.forName(cheese);
Intent ourIntent = new Intent(MenuActivity.this, ourClass);
startActivity(ourIntent);
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
您需要提及完全限定名称。
Class ourclass = Class.forName("com.example.music."+cheese);
还要确保packagename与清单文件中提到的名称相匹配。还要确保在清单中声明所有活动。
public static Class<?> forName (String className)
Added in API level 1
Returns a Class object which represents the class with the given name. The name should be the name of a non-primitive class, as described in the class definition. Primitive types can not be found using this method; use int.class or Integer.TYPE instead.
If the class has not yet been loaded, it is loaded and initialized first. This is done through either the class loader of the calling class or one of its parent class loaders. It is possible that a static initializer is run as a result of this call.
Throws
ClassNotFoundException if the requested class can not be found.
LinkageError if an error occurs during linkage
ExceptionInInitializerError if an exception occurs during static initialization of a class.
当我将意图线更改为&#34; ...新意图(MenuActivity.this, 起点。类)&#34;它仍然无法工作,所以我假设它 抛出异常已经在Class.forName()行中,因为 当我把那个Intent(MenuActivity.this,Starting point.class)&#34; 在try块之外它可以工作
您仍然拥有Class<?> ourClass = Class.forName(cheese);
,如果找不到请求的课程,您会看到它会抛出ClassNotFoundException
。你选择了packaname.classname