activity_list.xml文件代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 android:orientation="vertical" 5 android:layout_width="fill_parent" 6 android:layout_height="fill_parent"> 7 8 <ListView 9 android:id="@+id/listview" 10 android:layout_width="match_parent" 11 android:layout_height="match_parent"> 12 </ListView> 13 14 </LinearLayout>
ListActivity.java文件代码如下:
1 package com.example.sample_6_4; 2 3 import android.app.Dialog; 4 import android.graphics.Color; 5 import android.preference.DialogPreference; 6 import android.support.v7.app.AlertDialog; 7 import android.support.v7.app.AppCompatActivity; 8 import android.os.Bundle; 9 import android.view.View; 10 import android.view.ViewGroup; 11 import android.view.WindowManager; 12 import android.widget.ArrayAdapter; 13 import android.widget.BaseAdapter; 14 import android.widget.Button; 15 import android.widget.ListView; 16 import android.widget.TextView; 17 18 public class ListActivity extends AppCompatActivity { 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_list); 23 ListView lv = (ListView)findViewById(R.id.listview); 24 //做一个适配器来使用ListView 25 lv.setAdapter(new MyAdapter()); 26 } 27 class MyAdapter extends BaseAdapter{ 28 @Override 29 //返回条目的个数,列表的条目,例如一个屏幕显示多少条 30 public int getCount(){ 31 return 20; 32 } 33 @Override 34 //确定每个条目的布局和内容,position代表条目的位置,从0开始 35 public View getView(int position, View converView, ViewGroup parent){ 36 TextView tv = new TextView(ListActivity.this); 37 tv.setText("条目" + position); 38 tv.setTextSize(23); 39 tv.setTextColor(Color.BLUE); 40 return tv; 41 } 42 @Override 43 public Object getItem(int position){ 44 return null; 45 } 46 @Override 47 public long getItemId(int position){ 48 return 0; 49 } 50 } 51 }
效果如下: