我想在我的Android应用程序中获取一个简单的列表并用一些字符串填充它。为此,我实施了以下主要活动:
public class MainMenuActivity extends BaseActivity{
private ArrayList<String> teamList = new ArrayList<String>();
private ArrayAdapter<String> teamListAdapter;
private ListView teamListView;
protected void loadGUI() {
setContentView(R.layout.main_login);
teamListView = (ListView) findViewById(R.id.teamList);
teamListAdapter = new ArrayAdapter<String>(mContext, R.id.teamList, teamList);
teamListView.setAdapter(teamListAdapter);
addItem("test");
}
public void addItem(String item) {
teamList.add(item);
teamListAdapter.notifyDataSetChanged();
}
}
使用BaseActivity实现onCreate方法等的类:
public abstract class BaseActivity extends Activity {
protected Activity mActivity;
protected Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = this;
mContext = getApplicationContext();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public void onResume() {
super.onResume();
loadGUI();
}
protected abstract void loadGUI();
}
当我尝试运行时,我收到错误:
05-09 16:50:04.386: E/AndroidRuntime(12037): android.content.res.Resources$NotFoundException: Resource ID #0x7f070002 type #0x12 is not valid
这个错误是由addItem函数调用引起的,但我不知道这个函数有什么问题。有人看到可能出错的地方吗?
答案 0 :(得分:1)
您将错误类型的资源传递给ArrayAdaper的构造函数。参数2应该是包含在实例化视图时使用的TextView的布局文件的资源ID。
答案 1 :(得分:1)
您在适配器中使用了错误的ID。尝试更改此内容:
teamListAdapter = new ArrayAdapter<String>(mContext, R.id.teamList, teamList);
到此:
teamListAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, teamList);