我正在学习用于Android开发的newboston教程,我想知道是否有一个快速的解决方案来显示字符串值,而不需要它们与它们的类或活动名称相同,即字符串名称"SystemActivity“必须与其活动名称相同才能工作。问题是它在模拟器UI上显示为"SystemActivity“,我宁愿给它取一个更合适的名称.“启动系统”。
我很感谢你的帮助..。
这是我的代码:
String classes [] = {"SystemActivity","DietTips","About"};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
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);
String link = classes [position];
try{
Class ourClass = Class.forName("com.example.system." + link);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}}
发布于 2014-08-13 14:05:55
好吧,我建议你跳过本教程,因为它展示了一个糟糕的实践。您很少需要找到一个类的名称,而且您不应该这样做。一个简单的错误和你的应用程序不工作。
您应该修改您的代码,使其基于具有名称和类型的索引或包装对象。基于索引的方法将产生比当前方法更少的错误,包装器对象应该100%正确工作。
基于索引的:
onListItemClick(...., int position...){
Intent i;
switch(position){
case 0:
//SystemActivity
i = new Intent(Menu.this, SystemActivity.class);
break;
//other cases
}
startActivity(i);
}基于包装的:
public class Wrapper<T> {
String name;
Class<T> type;
public Wrapper(String n, Class<T> t){
name =n;
type = t;
}
String toString(){return name};
}
//Then pass these objects to your array adapter:
Wrapper wrapper1= new Wrapper("Start System",SystemActivity.class);
...
Wrapper[] wrappers = {wrapper1,wrapper2..}
setListAdapter(new ArrayAdapter<Wrapper>(...,wrappers,..));
onListItemClick(...){
Wrapper clicked = wrappers[position];
Intent i = new Intent(Menu.this, clicked.type);
startActivity(i);
}发布于 2014-08-13 13:40:32
创建一个包含用户友好名称和“类型”(即类型名称)的包装类,并使用自定义数组适配器来映射它。
这比简单地创建一个现成的适配器要复杂一些,但是尽早学习如何做到这一点是个好主意,因为大多数时候您将创建包含多个字符串的自定义列表,这将需要自定义适配器和自定义视图。
这看起来是一个很好的例子:http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/
如果有什么不清楚的地方,请告诉我,我会尽力提供更多帮助。
https://stackoverflow.com/questions/25286390
复制相似问题