
listview用法
显示项目列表是移动应用程序中非常常见的模式。 在制作教程时,经常会出现这种模式:我经常需要与数据进行交互,但是我不想花很多时间仅仅在显示数据时就花了很多,而这并不是本教程的重点。 那么,在Android中显示简单值列表(如字符串列表)的最简单方法是什么?
在Android SDK中,用于显示项目列表的小部件是ListView 。 列表视图必须始终从适配器类获取其数据。 该适配器类管理用于显示每个单独项目的布局,其行为方式以及数据本身。 在Android SDK中显示多个项目的所有其他小部件(例如微调器和网格)也需要适配器。
当我为使用Android保存数据的系列制作编织行计数器时,我需要显示数据库中所有项目的列表,但我想做到绝对最小。 项目的名称是字符串,因此我使用了Android SDK中的ArrayAdapter类来显示该字符串列表。 这是显示创建适配器并在列表视图中进行设置以显示项目列表的示例:
private ListView mListView;
@Override
protected void onStart()
{
super.onStart();
// Add the project titles to display in a list for the listview adapter.
List<String> listViewValues = new ArrayList<String>();
for (Project currentProject : mProjects) {
listViewValues.add(currentProject.getName());
}
// Initialise a listview adapter with the project titles and use it
// in the listview to show the list of project.
mListView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
listViewValues.toArray(new String[listViewValues.size()]));
mListView.setAdapter(adapter);
}
设置列表适配器后,还可以添加一个操作,以在单击某项时执行。 对于行计数器应用程序,单击一个项目将打开一个新活动,该活动显示所选项目的详细信息。
private ListView mListView;
@Override
protected void onStart()
{
[...]
// Sets a click listener to the elements of the listview so a
// message can be shown for each project.
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
// Get clicked project.
Project project = mProjects.get(position);
// Open the activity for the selected project.
Intent projectIntent = new Intent(MainActivity.this, ProjectActivity.class);
projectIntent.putExtra("project_id", project.getId());
MainActivity.this.startActivity(projectIntent);
}
如果您需要比默认布局更进一步,则需要创建自定义布局和适配器以按所需方式显示数据,但是此处显示的内容足以开始显示数据。 如果要运行该示例,可以在我的GitHub上找到完整的RowCounter项目,网址为http://github.com/CindyPotvin/RowCounter :列表视图是MainActivity.java文件。
翻译自: https://www.javacodegeeks.com/2015/01/display-a-string-list-in-an-android-listview.html
listview用法