【android基礎學習之二】——基礎控制項ListView

來源:互聯網
上載者:User

聲明:學習的書籍《Android應用開發揭秘》,這裡記錄學習該書籍的日誌,引用的相關代碼與總結描述,沒有商業的用途,完全是自我學習的一個記錄,剛剛學習不可避免會出現很多問題,若是有錯誤還請大家多多批評。

 

繼續前面的學習 

一、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卡的大小。

具體是什麼原因,暫時不是太清楚,後面深入學習會繼續關注該問題。

3.       在用android日誌LogCat的時候老是彈出一個視窗,內容為:"Copy" did not complete normally. Please see the log for more information. 
Argument not valid 

在網上也找到了答案:退出有道詞典,或者劃詞功能就可以了。如果不是有道詞典關閉翻譯軟體的劃詞功能。(的確很鬱悶,存在這個問題)

 

以下是該例子的執行個體代碼

 

public class Activity01 extends Activity {private static final String TAG = "TestListView";ListView listView;ListAdapter adapter;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);LinearLayout linearLayout = new LinearLayout(this);linearLayout.setOrientation(LinearLayout.VERTICAL);//設定布局LinearLayout的屬性linearLayout.setBackgroundColor(Color.BLACK);LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);//設定該LinearLayout下的子控制項的配置樣式listView = new ListView(this);listView.setBackgroundColor(Color.BLACK);linearLayout.addView(listView, param);// 添加listView到linearLayout布局 this.setContentView(linearLayout);ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();/*Cursor是個Interface,API中介紹:A mock Cursor class that isolates the test code from real Cursor implementation.  SQLiteCursor A Cursor implementation that exposes results from a query on a SQLiteDatabase. 【注意】:這裡擷取連絡人的資訊的游標對象,注意sdk2.0以後,API發生調整,People介面由ContactsContract.Contacts代替,自己參考《Android應用開發揭秘》執行個體4-4運行報錯,書中執行個體代碼:// ListAdapter是ListView和後台資料的橋樑ListAdapter adapter = new SimpleCursorAdapter(this,// 定義List中每一行的顯示模板// 表示每一行包含兩個資料項目android.R.layout.simple_list_item_2,// 資料庫的Cursor對象cur,// 從資料庫的NAME和NUMBER兩列中取資料new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup.NUMBER },// 與NAME和NUMBER對應的Viewsnew int[] { android.R.id.text1, android.R.id.text2 });運行上述提取方式會報'number'列不存在,說明在2.2的版本下PhoneLookup.NUMBER這個擷取方式不對*/Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);while (cursor.moveToNext()) {HashMap<String, Object> map = new HashMap<String, Object>();String phoneName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));map.put("ItemTitle", phoneName);// 連絡人姓名String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));//擷取連絡人行資料ID String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));//HAS_PHONE_NUMBER:一個標示用來說明:是否至少有一個電話. "1" 為真, "0" 假. if (hasPhone.compareTo("1") == 0) {Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);/*方法android.content.ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)其中第三個參數: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 作為條件過濾器,類似於一個SQL語句中where子句,若為空白,則返回所有行 */while (phones.moveToNext()) {//注意:ContactsContract.CommonDataKinds.Phone.NUMBER與之前sdk版本的擷取方式String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));String phoneTpye = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));map.put("ItemText", phoneNumber); // 多個號碼如何處理Log.d(TAG, "testNum=" + phoneNumber + "type:" + phoneTpye);}phones.close();}Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = "+ contactId, null, null);while (emails.moveToNext()) {String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));String emailType = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));Log.d(TAG, "testEmail=" + emailAddress + "type:" + emailType);}emails.close();listItem.add(map);}// 產生適配器的Item和動態數組對應的元素SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 資料來源android.R.layout.simple_list_item_2,// ListItem的XML實現// 動態數組與ImageItem對應的子項new String[] { "ItemTitle", "ItemText" },// ImageItem的XML檔案裡面的一個ImageView,兩個TextView IDnew int[] { android.R.id.text1, android.R.id.text2 });listView.setAdapter(listItemAdapter);cursor.close();/* 為m_ListView視圖添加setOnItemSelectedListener監聽 */listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){DisplayToast("滾動到第"+Long.toString(arg0.getSelectedItemId())+"項");}public void onNothingSelected(AdapterView<?> arg0){//沒有選中}});/* 為m_ListView視圖添加setOnItemClickListener監聽 */listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){//於對選中的項進行處理DisplayToast("選中了第"+Integer.toString(arg2+1)+"項");}});}private void DisplayToast(String str) {Toast.makeText(this, str, Toast.LENGTH_SHORT).show();}}

效果:(左圖為選擇事件,右圖為點擊事件)
 

當然也可以把選擇事件setOnItemSelectedListener與點擊事件setOnItemClickListener自己修改,如網上例子給出,選擇事件為傳送簡訊,點擊事件為撥打到電話。

listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {// TODO Auto-generated method stub// openToast("滾動到:"+arg0.getSelectedItemId());// 簡訊發送setTitle("選擇" + arg2 + "項目");openToast("選擇" + arg0.getSelectedItemId() + "項目");RelativeLayout lr = (RelativeLayout) arg1;TextView mText = (TextView) lr.getChildAt(1);openToast(mText.getText().toString());String number = mText.getText().toString();Log.d(TAG, "number=" + number);// 判斷電話號碼的有效性if (PhoneNumberUtils.isGlobalPhoneNumber(number)) {Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto://" + number));intent.putExtra("sms_body", "The SMS text");startActivity(intent);}}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// openToast("Click"+Integer.toString(position+1)+"項目");RelativeLayout lr = (RelativeLayout) arg1;TextView mText = (TextView) lr.getChildAt(1);openToast(mText.getText().toString());String number = mText.getText().toString();Log.d(TAG, "number=" + number);// 判斷電話號碼的有效性if (PhoneNumberUtils.isGlobalPhoneNumber(number)) {Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel://" + number));startActivity(intent);}}});

 

通過兩天的學習才真正解決了ListView控制項的學習,雖然時間比較長,還是學到很多東西,繼續加油。

 

學習到P63頁

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.