简单的Android ListView示例
时间:2020-02-23 14:29:29 来源:igfitidea点击:
在本教程中,我们将创建简单的ListView。
ListView是我们在垂直订单中排列列表项的视图。
它是非常流行的小部件,几乎在每个应用程序中使用。
在本教程中,我将创建一个非常简单的列表视图。
如果要创建一些具有相同行的图像和文本的复杂列表视图,则可以通过Android自定义ListView示例。
第1步:创建项目
创建一个Android应用程序ProjectNamed"AndroidListViewExampleApp"。
第2步:创建布局
更改RES - >布局 - > Activity_main.xml如下所示:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.theitroad.androidlistviewexampleapp.MainActivity">
<ListView
android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
</RelativeLayout>
第3步:创建MainActivity
更改src/main/packageName/mainActivity.java如下:
package com.theitroad.androidlistviewexampleapp;
import android.app.ListActivity;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String[] listofCountries={"Netherlands","China","Nepal","Bhutan"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, listofCountries));
TextView textView = new TextView(this);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setText("List of Countries");
ListView listView=(ListView)findViewById(android.R.id.list);
listView.addHeaderView(textView);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Toast.makeText(this, "You have selected : " + listofCountries[position-1]+ " as country", Toast.LENGTH_LONG).show();
}
}
如果我们注意到,我们的主动率将列出作为列表具有专门用于ListView的方法。
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, listofCountries));
每当我们创建ListView时,我们需要为每行设置视图,并且我们还需要提供定义每行布局的文件。
在此示例中,我们使用的是android.r.layout.simple_list_item_1,它是Android的预定布局文件。

