ListView和各种Adapter的使用

http://gundumw100.iteye.com/blog/875967

 

1,和最简单的ArrayAdapter的使用:

Java代码
  1. package com.wt.app;
  2. import android.app.ListActivity;
  3. import android.os.Bundle;
  4. import android.widget.ArrayAdapter;
  5. import android.widget.ListAdapter;
  6. public class App extends ListActivity {
  7. String[] array={/*"aaa","bbb","ccc"*/};
  8. /** Called when the activity is first created. */
  9. @Override
  10. public void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.main);
  13. //为空时的显示内容
  14. this.getListView().setEmptyView(findViewById(R.id.empty));
  15. ListAdapter adapter=new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,array);
  16. this.setListAdapter(adapter);
  17. }
  18. }
package com.wt.app;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

public class App extends ListActivity {
	String[] array={/*"aaa","bbb","ccc"*/};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //为空时的显示内容
        this.getListView().setEmptyView(findViewById(R.id.empty));
        
        ListAdapter adapter=new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,array);
        this.setListAdapter(adapter);
    }
}


 

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <ListView
  8. android:id="@+id/android:list"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. />
  12. <TextView
  13. android:id="@+id/empty"
  14. android:layout_width="fill_parent"
  15. android:layout_height="wrap_content"
  16. android:gravity="center_vertical"
  17. android:text="Nothing"
  18. />
  19. </LinearLayout>



2,和SimpleAdapter的使用:

Java代码 复制代码 收藏代码
  1. package com.wt.app;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import android.app.Activity;
  5. import android.os.Bundle;
  6. import android.view.ContextMenu;
  7. import android.view.MenuItem;
  8. import android.view.View;
  9. import android.view.ContextMenu.ContextMenuInfo;
  10. import android.view.View.OnCreateContextMenuListener;
  11. import android.widget.AdapterView;
  12. import android.widget.ListView;
  13. import android.widget.SimpleAdapter;
  14. import android.widget.AdapterView.OnItemClickListener;
  15. public class App extends Activity {
  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.main);
  20. //绑定Layout里面的ListView
  21. ListView list = (ListView) findViewById(R.id.ListView01);
  22. //生成动态数组,加入数据
  23. ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
  24. int[] images=new int[]{android.R.drawable.ic_menu_add,android.R.drawable.ic_menu_delete,android.R.drawable.ic_menu_edit,android.R.drawable.ic_menu_view};
  25. for(int i=0;i<4;i++)
  26. {
  27. HashMap<String, Object> map = new HashMap<String, Object>();
  28. map.put("itemImage", images[i]);//图像资源的ID
  29. map.put("itemTitle", "Title "+i);
  30. map.put("itemText", "this is Text "+i);
  31. listItem.add(map);
  32. }
  33. //生成适配器的Item和动态数组对应的元素
  34. SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//数据源
  35. R.layout.row,//ListItem的XML实现
  36. //动态数组与ImageItem对应的子项
  37. new String[] {"itemImage","itemTitle", "itemText"},
  38. //ImageItem的XML文件里面的一个ImageView,两个TextView ID
  39. new int[] {R.id.itemImage,R.id.itemTitle,R.id.itemText}
  40. );
  41. //添加并且显示
  42. list.setAdapter(listItemAdapter);
  43. //添加点击
  44. list.setOnItemClickListener(new OnItemClickListener() {
  45. public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
  46. long arg3) {
  47. setTitle("点击第"+arg2+"个项目");
  48. }
  49. });
  50. //添加长按点击
  51. list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
  52. public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
  53. menu.setHeaderTitle("长按菜单-ContextMenu");
  54. menu.add(0, 0, 0, "弹出长按菜单0");
  55. menu.add(0, 1, 0, "弹出长按菜单1");
  56. }
  57. });
  58. }
  59. //长按菜单响应函数
  60. @Override
  61. public boolean onContextItemSelected(MenuItem item) {
  62. setTitle("点击了长按菜单里面的第"+item.getItemId()+"个项目");
  63. return super.onContextItemSelected(item);
  64. }
  65. }
package com.wt.app;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class App extends Activity {
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //绑定Layout里面的ListView
        ListView list = (ListView) findViewById(R.id.ListView01);
        
        //生成动态数组,加入数据
        ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
        int[] images=new int[]{android.R.drawable.ic_menu_add,android.R.drawable.ic_menu_delete,android.R.drawable.ic_menu_edit,android.R.drawable.ic_menu_view};
        for(int i=0;i<4;i++)
        {
        	HashMap<String, Object> map = new HashMap<String, Object>();
        	map.put("itemImage", images[i]);//图像资源的ID
        	map.put("itemTitle", "Title "+i);
        	map.put("itemText", "this is Text "+i);
        	listItem.add(map);
        }
        //生成适配器的Item和动态数组对应的元素
        SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//数据源 
            R.layout.row,//ListItem的XML实现
            //动态数组与ImageItem对应的子项        
            new String[] {"itemImage","itemTitle", "itemText"}, 
            //ImageItem的XML文件里面的一个ImageView,两个TextView ID
            new int[] {R.id.itemImage,R.id.itemTitle,R.id.itemText}
        );
       
        //添加并且显示
        list.setAdapter(listItemAdapter);
        //添加点击
        list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				setTitle("点击第"+arg2+"个项目");
			}
		});
        
      //添加长按点击
        list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			
			public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("长按菜单-ContextMenu");   
				menu.add(0, 0, 0, "弹出长按菜单0");
				menu.add(0, 1, 0, "弹出长按菜单1");   
			}
		}); 
    }
	
	//长按菜单响应函数
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		setTitle("点击了长按菜单里面的第"+item.getItemId()+"个项目"); 
		return super.onContextItemSelected(item);
	}
}


main.xml

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <ListView android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:id="@+id/ListView01"
  10. />
  11. </LinearLayout>\


row.xml

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. android:id="@+id/RelativeLayout01"
  4. android:layout_width="fill_parent"
  5. xmlns:android="http://schemas.android.com/apk/res/android"
  6. android:layout_height="wrap_content"
  7. android:paddingTop="4dip"
  8. android:paddingBottom="4dip"
  9. android:paddingLeft="12dip"
  10. android:paddingRight="12dip">
  11. <ImageView
  12. android:paddingTop="12dip"
  13. android:layout_alignParentRight="true"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:id="@+id/itemImage"
  17. />
  18. <TextView
  19. android:layout_height="wrap_content"
  20. android:textSize="20dip"
  21. android:layout_width="fill_parent"
  22. android:id="@+id/itemTitle"
  23. />
  24. <TextView
  25. android:layout_height="wrap_content"
  26. android:layout_width="fill_parent"
  27. android:layout_below="@+id/itemTitle"
  28. android:id="@+id/itemText"
  29. />
  30. </RelativeLayout>



3,和SimpleCursorAdapter的使用:

Java代码 复制代码 收藏代码
  1. package com.wt.app;
  2. import android.app.Activity;
  3. import android.app.PendingIntent;
  4. import android.content.ContentUris;
  5. import android.content.Intent;
  6. import android.database.Cursor;
  7. import android.database.CursorWrapper;
  8. import android.graphics.Color;
  9. import android.net.Uri;
  10. import android.os.Bundle;
  11. import android.provider.Contacts.People;
  12. import android.telephony.PhoneNumberUtils;
  13. import android.telephony.gsm.SmsManager;
  14. import android.util.Log;
  15. import android.view.ContextMenu;
  16. import android.view.MenuItem;
  17. import android.view.View;
  18. import android.view.ContextMenu.ContextMenuInfo;
  19. import android.view.View.OnCreateContextMenuListener;
  20. import android.widget.AdapterView;
  21. import android.widget.LinearLayout;
  22. import android.widget.ListAdapter;
  23. import android.widget.ListView;
  24. import android.widget.SimpleCursorAdapter;
  25. import android.widget.Toast;
  26. public class App extends Activity {
  27. private static final String TAG="App";
  28. ListView listView;
  29. ListAdapter adapter;
  30. /** Called when the activity is first created. */
  31. @Override
  32. public void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. // setContentView(R.layout.main);
  35. LinearLayout linearLayout=new LinearLayout(this);
  36. linearLayout.setOrientation(LinearLayout.VERTICAL);
  37. linearLayout.setBackgroundColor(Color.BLACK);
  38. LinearLayout.LayoutParams param=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
  39. listView=new ListView(this);
  40. listView.setBackgroundColor(Color.BLACK);
  41. linearLayout.addView(listView,param);
  42. this.setContentView(linearLayout);
  43. //从数据库获取联系人姓名和电话号码
  44. Cursor cur=this.getContentResolver().query(People.CONTENT_URI,null, null,null,null);
  45. adapter=new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cur,new String[]{People.NAME,People.NUMBER},new int[]{android.R.id.text1,android.R.id.text2});
  46. this.startManagingCursor(cur);
  47. listView.setAdapter(adapter);
  48. //listView.setEmptyView(findViewById(R.id.empty));
  49. listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
  50. public void onItemSelected(AdapterView<?> arg0, View arg1,
  51. int arg2, long arg3) {
  52. // TODO Auto-generated method stub
  53. //openToast("滚动到:"+arg0.getSelectedItemId());
  54. //短信发送
  55. // PendingIntent pi = PendingIntent.getActivity(App.this,0,new Intent(App.this,App.class),0);
  56. // SmsManager sms = SmsManager.getDefault();
  57. // sms.sendTextMessage("5554", null, "message", pi, null);
  58. }
  59. public void onNothingSelected(AdapterView<?> arg0) {
  60. // TODO Auto-generated method stub
  61. }
  62. });
  63. listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
  64. public void onItemClick(AdapterView<?> arg0, View arg1, int position,
  65. long arg3) {
  66. // TODO Auto-generated method stub
  67. // String[] names=((CursorWrapper)listView.getItemAtPosition(position)).getColumnNames();
  68. //从指针的封装类中获得选中项的电话号码并拨号
  69. CursorWrapper wrapper=(CursorWrapper)listView.getItemAtPosition(position);
  70. int columnIndex=wrapper.getColumnIndex(People.NUMBER);
  71. if(!wrapper.isNull(columnIndex)){
  72. String number=wrapper.getString(columnIndex);
  73. Log.d(TAG,"number="+number);
  74. // //判断电话号码的有效性
  75. if(PhoneNumberUtils.isGlobalPhoneNumber(number)){
  76. Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel://"+ number));
  77. startActivity(intent);
  78. }
  79. }
  80. /*
  81. //直接拨号,需要CALL_PHONE权限
  82. Intent intent=new Intent(Intent.ACTION_CALL);
  83. Cursor c=(Cursor)adapter.getItem(position);
  84. long phoneID=c.getLong(c.getColumnIndex(People.PRIMARY_PHONE_ID));
  85. intent.setData(ContentUris.withAppendedId(android.provider.
  86. Contacts.Phones.CONTENT_URI, phoneID));
  87. startActivity(intent);
  88. */
  89. }
  90. });
  91. //添加长按点击,弹出快显菜单
  92. listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
  93. public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
  94. menu.setHeaderTitle("你想要...?").setHeaderIcon(R.drawable.icon);
  95. menu.add(0, 0, 0, "删除").setIcon(R.drawable.icon);
  96. menu.add(0, 1, 0, "修改").setIcon(R.drawable.icon);
  97. }
  98. });
  99. }
  100. //长按菜单响应函数
  101. @Override
  102. public boolean onContextItemSelected(MenuItem item) {
  103. //setTitle("点击了长按菜单里面的第"+item.getItemId()+"个项目");
  104. openToast("你点击了"+item.getTitle());
  105. return super.onContextItemSelected(item);
  106. }
  107. private void openToast(String str){
  108. Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
  109. }
  110. }
package com.wt.app;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.telephony.PhoneNumberUtils;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class App extends Activity {
	private static final String TAG="App";
	ListView listView;
	ListAdapter adapter;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.main);
        LinearLayout linearLayout=new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setBackgroundColor(Color.BLACK);
        LinearLayout.LayoutParams param=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        
        listView=new ListView(this);
        listView.setBackgroundColor(Color.BLACK);
        
        linearLayout.addView(listView,param);
        
        this.setContentView(linearLayout);
        
        //从数据库获取联系人姓名和电话号码
        Cursor cur=this.getContentResolver().query(People.CONTENT_URI,null, null,null,null);
        adapter=new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cur,new String[]{People.NAME,People.NUMBER},new int[]{android.R.id.text1,android.R.id.text2});
        this.startManagingCursor(cur);
        listView.setAdapter(adapter);
        //listView.setEmptyView(findViewById(R.id.empty));
        
        listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				//openToast("滚动到:"+arg0.getSelectedItemId());
				//短信发送
//				PendingIntent pi = PendingIntent.getActivity(App.this,0,new Intent(App.this,App.class),0);
//				SmsManager sms = SmsManager.getDefault();  
//				sms.sendTextMessage("5554", null, "message", pi, null); 
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
        	
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
//				String[] names=((CursorWrapper)listView.getItemAtPosition(position)).getColumnNames();
				//从指针的封装类中获得选中项的电话号码并拨号
				CursorWrapper wrapper=(CursorWrapper)listView.getItemAtPosition(position);
				int columnIndex=wrapper.getColumnIndex(People.NUMBER);
				if(!wrapper.isNull(columnIndex)){
					String number=wrapper.getString(columnIndex);
					Log.d(TAG,"number="+number);
	//				//判断电话号码的有效性
					if(PhoneNumberUtils.isGlobalPhoneNumber(number)){
						Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel://"+ number));
						startActivity(intent);
					}
				}
/*
//直接拨号,需要CALL_PHONE权限
				Intent intent=new Intent(Intent.ACTION_CALL);
                Cursor c=(Cursor)adapter.getItem(position);
                long phoneID=c.getLong(c.getColumnIndex(People.PRIMARY_PHONE_ID));
                intent.setData(ContentUris.withAppendedId(android.provider.
                                             Contacts.Phones.CONTENT_URI, phoneID));
                startActivity(intent);
                */

			}
        });
      //添加长按点击,弹出快显菜单
        listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			
			public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("你想要...?").setHeaderIcon(R.drawable.icon); 
				menu.add(0, 0, 0, "删除").setIcon(R.drawable.icon);
				menu.add(0, 1, 0, "修改").setIcon(R.drawable.icon);   
			}
		});
    }
  //长按菜单响应函数
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		//setTitle("点击了长按菜单里面的第"+item.getItemId()+"个项目"); 
		openToast("你点击了"+item.getTitle());
		return super.onContextItemSelected(item);
	}
    private void openToast(String str){
    	Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
    }
}


 

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.wt.app"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <application android:icon="@drawable/icon" android:label="@string/app_name">
  7. <activity android:name=".App"
  8. android:label="@string/app_name">
  9. <intent-filter>
  10. <action android:name="android.intent.action.MAIN" />
  11. <category android:name="android.intent.category.LAUNCHER" />
  12. </intent-filter>
  13. <!-- 点击拨号时,询问调用默认的程序还是调用本程序拨号 -->
  14. <intent-filter>
  15. <action android:name="android.Intent.Action.CALL_BUTTON" />
  16. <category android:name="android.Intent.Category.DEFAULT" />
  17. </intent-filter>
  18. </activity>
  19. </application>
  20. <uses-permission android:name="android.permission.READ_CONTACTS" />
  21. <uses-permission android:name="android.permission.CALL_PHONE"/>
  22. <uses-sdk android:minSdkVersion="3" />
  23. </manifest>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值