Android中ListView用法实例分析

时间:2022-03-21 08:15:27

本文实例分析了AndroidListView用法。分享给大家供大家参考,具体如下:

通过在Layout中添加ListView Widget可以达到在页面布局具有列表效果的交互页面。在这里通过举例来说明怎样在Layout中添加ListView以及怎样应用。

配合设计了两个事件Listener:  OnItemSelectedListener事件为鼠标的滚轮转动时所选择的值;OnItemClickListener事件则为当鼠标单击时,所触发的事件。由此可以区别出list中的“选择”与“单击”差异。

使用ArrayAdapter(Context  context, int  textViewResourceId , T[] objects)这个构造器,其中textViewResourceId是定义在“res/layout/my_simple_list_item.xml”里的资源ResourceID(R.layout.my_simple_list_item),里面使用CheckedTextView来取得ListView中选择的项目。

程序中使用了LinearLayout对象,动态地将TextView与ListView附加进原有的Layout布局当中。用LinearLayout.LayoutParams来创建对象param1,再调用LinearLayout的addView方法将TextView和ListView以及params对象传入。

程序如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class A07Activity extends Activity {
 private static final String[]week="sunday","monday","tuesday","wednesday","thursday","friday","saturday"};
 private TextView tv;
 private ListView lv;
 private ArrayAdapter<String> aa;
 private LinearLayout ll;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tv=new TextView(this);
    tv.setText(R.string.title);
    tv.setTextColor(Color.RED);
    lv=new ListView(this);
    lv.setBackgroundColor(Color.GREEN);
    ll=new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.setBackgroundColor(android.graphics.Color.YELLOW);
    aa=new ArrayAdapter<String>(A07Activity.this,R.layout.my_simple_list,week);
    lv.setAdapter(aa);
    LinearLayout.LayoutParams params01=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    ll.addView(lv, params01);
    LinearLayout.LayoutParams params02=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    ll.addView(tv, params02);
    setContentView(ll);
    lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  @Override
  public void onItemSelected(AdapterView<?> arg0, View arg1,
   int arg2, long arg3) {
  // TODO Auto-generated method stub
  tv.setText("你选择的是:"+arg0.getSelectedItem().toString());
  }
  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
  // TODO Auto-generated method stub
  }
 });
  lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
   long arg3) {
  // TODO Auto-generated method stub
  tv.setText("你选择的是:"+week[arg2]);
  }
 });
  }
}

res/layout/my_simple_list.xml如下:

?
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/myCheckedTextView1"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
/>

希望本文所述对大家Android程序设计有所帮助。