本文实例分析了Android中ListActivity用法。分享给大家供大家参考,具体如下:
程序如下:
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
48
49
50
51
52
53
54
55
56
57
58
59
|
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class A08Activity extends ListActivity {
private int selectedItem=- 1 ;
private ArrayAdapter<String> aa;
private String[] s;
private static final int MENU_LIST01=Menu.FIRST;
private static final int MENU_LIST02=Menu.FIRST+ 1 ;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
//setContentView(R.layout.main);
}
protected void onListItemClick(ListView l,View v, int position, long id){
selectedItem=position;
Toast.makeText(A08Activity. this , s[selectedItem], Toast.LENGTH_LONG).show();
super .onListItemClick(l, v, position, id);
}
public boolean onCreateOptionsMenu(Menu menu){
int idGroup1= 0 ;
int orderMenuItem01=Menu.NONE;
int orderMenuItem02=Menu.NONE+ 1 ;
menu.add(idGroup1, MENU_LIST01, orderMenuItem01, R.string.str_menu_list01);
menu.add(idGroup1, MENU_LIST02, orderMenuItem02, R.string.str_menu_list02);
return super .onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case MENU_LIST01:
s= new String[]{
getResources().getString(R.string.str_list01),
getResources().getString(R.string.str_list02),
getResources().getString(R.string.str_list03),
getResources().getString(R.string.str_list04)
};
aa= new ArrayAdapter<String>(A08Activity. this ,R.layout.main,s);
A08Activity. this .setListAdapter(aa);
break ;
case MENU_LIST02:
s= new String[]{
getResources().getString(R.string.str_list05),
getResources().getString(R.string.str_list06),
getResources().getString(R.string.str_list07),
getResources().getString(R.string.str_list08)
};
aa= new ArrayAdapter<String>(A08Activity. this ,R.layout.main,s);
A08Activity. this .setListAdapter(aa);
break ;
}
return super .onOptionsItemSelected(item);
}
}
|
res/layout/main.xml如下:
1
2
3
4
5
6
7
8
|
<? xml version = "1.0" encoding = "utf-8" ?>
< TextView
xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/myTextView1"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:text = "@string/hello"
/>
|
ListActivity的类型布局配置应用程序,常用来显示菜单列表、列表明细项目。它不必像Activity一样,可以不使用setContentView来设置版型Layout才能显示页面,ListActivity可以在不必重写protected void onCreate(Bundle savedInstanceState)的情况下,直接将列表加载至ListActivity中,常用友如投票选项选择、多项目列表条列显示、文件资源管理器等。
本例在ListActivity中创建两个Menu菜单功能,动态显示不同的列表项目到ListActivity上,而为了捕捉用户在ListActivity上的单击项目,重写了onListItemClick()方法来获取用户单击的ListItem项目,为了简化程序,用Toast来提示。
希望本文所述对大家Android程序设计有所帮助。