现在的位置: 首页 > 综合 > 正文

基础控件ListView

2013年12月12日 ⁄ 综合 ⁄ 共 8059字 ⁄ 字号 评论关闭
一、TextView文本框(省略)。
二、列表ListView

针对列表的事件:
(1)当鼠标滚动时会触发:setOnItemSelectedListener事件;
(2)点击时触发:setOnItemClickListener事件

实例分析:对电话本联系人的信息进行操作。 布局格式:LinearLayout中显示ListView
【注意】是同个ListAdapter将获得的电话本数据与ListView关联起来,将ListAdapter添加到ListView中。

【遇到问题困难】:该实例遇到很多困难,因为才是学习Android的第2天,很多内容还不了解,比如Android下数据获取与绑定,相关参数与方法的使用,很多需要学习与掌握,查看API以及,在网上查找了很多资料。
1.       联系人与电话的获取,1.5以后API发生变化,所以获取方式就要修改,参考代码。
2.       启动模拟器时,弹出SDL_app:emulator.exe 应用程序错误:
解决方法:删除该模拟器的SD卡的大小。
1.gif

具体是什么原因,暂时不是太清楚,后面深入学习会继续关注该问题。
3.       在用android日志LogCat的时候老是弹出一个窗口,内容为:"Copy" did not complete normally. Please see the log for more information.  
Argument not valid
在网上也找到了答案:退出有道词典,或者划词功能就可以了。如果不是有道词典关闭翻译软件的划词功能。(的确很郁闷,存在这个问题)
以下是该例子的实例代码

  1. public class Activity01 extends Activity {  
  2.     private static final String TAG = "TestListView";  
  3.     ListView listView;  
  4.     ListAdapter adapter;  
  5.   
  6.     public void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.          
  9.         LinearLayout linearLayout = new LinearLayout(this);  
  10.         linearLayout.setOrientation(LinearLayout.VERTICAL); //设置布局LinearLayout的属性  
  11.         linearLayout.setBackgroundColor(Color.BLACK);  
  12.         LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(  
  13.                 LinearLayout.LayoutParams.FILL_PARENT,  
  14.                 LinearLayout.LayoutParams.WRAP_CONTENT);    //设置该LinearLayout下的子控件的布局样式  
  15.          
  16.         listView = new ListView(this);  
  17.         listView.setBackgroundColor(Color.BLACK);  
  18.   
  19.         linearLayout.addView(listView, param);              // 添加listView到linearLayout布局   
  20.         this.setContentView(linearLayout);  
  21.   
  22.         ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();  
  23.          
  24.         /*Cursor是个Interface,API中介绍:A mock Cursor class that isolates the test code from real Cursor implementation.   
  25.         SQLiteCursor A Cursor implementation that exposes results from a query on a SQLiteDatabase.  
  26.         【注意】:这里获取联系人的信息的光标对象,注意sdk2.0以后,API发生调整,People接口由ContactsContract.Contacts代替,
  27.         自己参考《Android应用开发揭秘》实例4-4运行报错,书中实例代码:
  28.         // ListAdapter是ListView和后台数据的桥梁
  29.         ListAdapter adapter = new SimpleCursorAdapter(this,
  30.             // 定义List中每一行的显示模板
  31.             // 表示每一行包含两个数据项
  32.             android.R.layout.simple_list_item_2,
  33.             // 数据库的Cursor对象
  34.             cur,
  35.             // 从数据库的NAME和NUMBER两列中取数据
  36.             new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup.NUMBER },
  37.             // 与NAME和NUMBER对应的Views
  38.             new int[] { android.R.id.text1, android.R.id.text2 });      
  39.             运行上述提取方式会报'number'列不存在,说明在2.2的版本下PhoneLookup.NUMBER这个获取方式不对
  40.         */  
  41.         Cursor cursor = getContentResolver().query(  
  42.                 ContactsContract.Contacts.CONTENT_URI, null, null, null, null);  
  43.         while (cursor.moveToNext()) {  
  44.             HashMap<String, Object> map = new HashMap<String, Object>();  
  45.             String phoneName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));  
  46.             map.put("ItemTitle", phoneName);// 联系人姓名  
  47.             String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));//获取联系人行数据ID   
  48.             String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));  
  49.             //HAS_PHONE_NUMBER:一个标示用来说明:是否至少有一个电话. "1" 为真, "0" 假.   
  50.   
  51.             if (hasPhone.compareTo("1") == 0) {  
  52.                 Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,  
  53.                         ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);  
  54.                 /*方法android.content.ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
  55.                     其中第三个参数:String selection,作用如API:A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI
  56.                     作为条件过滤器,类似于一个SQL语句中where子句,若为空,则返回所有行
  57.                  */  
  58.                 while (phones.moveToNext()) {  
  59.                     //注意:ContactsContract.CommonDataKinds.Phone.NUMBER与之前sdk版本的获取方式  
  60.                     String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));  
  61.                     String phoneTpye = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));  
  62.   
  63.                     map.put("ItemText", phoneNumber); // 多个号码如何处理  
  64.   
  65.                     Log.d(TAG, "testNum=" + phoneNumber + " type:" + phoneTpye);  
  66.                 }  
  67.                 phones.close();  
  68.             }  
  69.             Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,  
  70.                     ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = "+ contactId, null, null);  
  71.             while (emails.moveToNext()) {  
  72.                 String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));  
  73.                 String emailType = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));  
  74.   
  75.                 Log.d(TAG, "testEmail=" + emailAddress + "  type:" + emailType);  
  76.             }  
  77.             emails.close();  
  78.   
  79.             listItem.add(map);  
  80.         }  
  81.   
  82.         // 生成适配器的Item和动态数组对应的元素  
  83.         SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 数据源  
  84.                 android.R.layout.simple_list_item_2,// ListItem的XML实现  
  85.                 // 动态数组与ImageItem对应的子项  
  86.                 new String[] { "ItemTitle", "ItemText" },  
  87.                 // ImageItem的XML文件里面的一个ImageView,两个TextView ID  
  88.                 new int[] { android.R.id.text1, android.R.id.text2 });  
  89.   
  90.         listView.setAdapter(listItemAdapter);  
  91.         cursor.close();  
  92.   
  93.         /* 为m_ListView视图添加setOnItemSelectedListener监听 */  
  94.         listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {  
  95.             public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){   
  96.                 DisplayToast("滚动到第"+Long.toString(arg0.getSelectedItemId())+"项");  
  97.             }  
  98.   
  99.             public void onNothingSelected(AdapterView<?> arg0){  
  100.                 //没有选中  
  101.             }  
  102.         });  
  103.   
  104.         /* 为m_ListView视图添加setOnItemClickListener监听 */  
  105.         listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  106.             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){  
  107.                 //于对选中的项进行处理  
  108.                 DisplayToast("选中了第"+Integer.toString(arg2+1)+"项");  
  109.             }  
  110.         });  
  111.     }  
  112.   
  113.     private void DisplayToast(String str) {  
  114.         Toast.makeText(this, str, Toast.LENGTH_SHORT).show();  
  115.     }  

复制代码

效果:(左图为选择事件,右图为点击事件)
2.gif3.gif

当然也可以把选择事件setOnItemSelectedListener与点击事件setOnItemClickListener自己修改,如网上例子给出,选择事件为发送短信,点击事件为拨打电话。
  1. listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {  
  2.   
  3.             public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {  
  4.                 // TODO Auto-generated method stub  
  5.                 // openToast("滚动到:"+arg0.getSelectedItemId());  
  6.                 // 短信发送  
  7.                 setTitle("选择" + arg2 + "项目");  
  8.                 openToast("选择" + arg0.getSelectedItemId() + "项目");  
  9.                 RelativeLayout lr = (RelativeLayout) arg1;  
  10.                 TextView mText = (TextView) lr.getChildAt(1);  
  11.                 openToast(mText.getText().toString());  
  12.   
  13.                 String number = mText.getText().toString();  
  14.                 Log.d(TAG, "number=" + number);  
  15.                 // 判断电话号码的有效性  
  16.                 if (PhoneNumberUtils.isGlobalPhoneNumber(number)) {  
  17.                     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto://" + number));  
  18.                     intent.putExtra("sms_body", "The SMS text");  
  19.                     startActivity(intent);  
  20.                 }  
  21.             }  
  22.   
  23.             public void onNothingSelected(AdapterView<?> arg0) {  
  24.                 // TODO Auto-generated method stub  
  25.   
  26.             }  
  27.   
  28.         });  
  29.   
  30.         listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  31.   
  32.             public void onItemClick(AdapterView<?> arg0, View arg1,  
  33.                     int position, long arg3) {  
  34.                 // TODO Auto-generated method stub  
  35.                 // openToast("Click"+Integer.toString(position+1)+"项目");  
  36.                 RelativeLayout lr = (RelativeLayout) arg1;  
  37.                 TextView mText = (TextView) lr.getChildAt(1);  
  38.                 openToast(mText.getText().toString());  
  39.   
  40.                 String number = mText.getText().toString();  
  41.                 Log.d(TAG, "number=" + number);  
  42.                 // 判断电话号码的有效性  
  43.                 if (PhoneNumberUtils.isGlobalPhoneNumber(number)) {  
  44.                     Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel://" + number));  
  45.                     startActivity(intent);  
  46.                 }  
  47.             }  
  48.         });  

复制代码

通过两天的学习才真正解决了ListView控件的学习,虽然时间比较长,还是学到很多东西,继续加油。

抱歉!评论已关闭.