【发布时间】:2014-05-12 11:32:43
【问题描述】:
我想要的是获得与项目数量一样多的文本视图(列表行)。表示for循环。请帮我解决CODERS。我只得到最后一项,所以我“硬编码”了它。
公共类 AllNotes 扩展 Activity {
Button button;
TextView textview;
// trial copy code from other from net
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_notes);
String path = Environment.getExternalStorageDirectory().toString()+ "/" + FirstOneAct.foldername;
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "" + file.length);
Toast.makeText(this, "" + file.length ,Toast.LENGTH_SHORT).show();
for (int i=0; i < file.length; i++)
{
// trial copy code from other from net
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayList<String> planetList = new ArrayList<String>();
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
listAdapter.add(file[0].getName());
listAdapter.add(file[1].getName());
listAdapter.add(file[2].getName());
listAdapter.add(file[3].getName());
listAdapter.add(file[4].getName());
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
Log.d("Files", "FileName:" + file[i].getName());
Toast.makeText(getApplicationContext(), file[i].getName(),Toast.LENGTH_LONG).show();
}
/*// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter ); */
}
}
【问题讨论】:
-
listAdapter.add(file[i].getName());有什么问题? -
先生,这一行只显示最后一项。这就是我硬编码最多 5 个项目的原因。
-
这是因为您每次在循环中重新分配适配器:这一行
mainListView.setAdapter( listAdapter );应该在循环之后 -
我之前剪掉了那条线并粘贴了,(现在在哪里)。但没有发生任何变化。
-
不,它需要在之后。切割之前的位置。
标签: android for-loop arraylist