標籤:
在物聯網學習中我需要用到Android來擷取PC端資料庫內的表資料並顯示在螢幕上,因此我決定用WebService來串連資料庫擷取資料,用ListView組件顯示資料。這裡我將擷取到的資料存入List泛型中,就不示範如何擷取資料。
ListView是Android常用的一個組件,可以以列表的方式顯示資料,並且能自適應內容。ListView組件並非一次載入所有資料,而是螢幕顯示多少行資料就載入多少行資料。但往下拖動時再載入新的一行資料,且當螢幕第一行被移出螢幕時記憶體會被回收,往下同理。所以當資料量很大時不用擔心用ListView會出問題。
ListView使用setAdapter()方法來綁定資料配接器,這裡我選擇 使用一個類來繼承BaseAdapter,BaseAdapter類有四個必須實現的方法,getCount(),getView(),getItem(),getItemId()。其中,重要的方法為getCount()和getView()
public class Myadapter extends BaseAdapter{ @Override public int getCount() { return null; //返回資料的總行數 } @Override public View getView(int position, View convertView, ViewGroup parent) { return null; //返回一行資料 } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; }}
每當載入新一條資料時便會調用一次getVIew(int position, View convertView, ViewGroup parent)方法,其中position為將要載入的資料的行號。
為了讓資料顯示的更好看我們可以先在res/layout檔案夾下建立樣式表。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:id="@+id/ID" android:gravity="center" android:text="ID" android:background="#22000000" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"/> <!--每列的樣式--> <View android:layout_width="1dp" android:background="#000000" android:layout_height="wrap_content"/> <!--每列後的豎線--> <TextView android:id="@+id/NAME" android:gravity="center" android:background="#22000000" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="NAME"/> <View android:layout_width="1dp" android:background="#000000" android:layout_height="wrap_content"/> <TextView android:id="@+id/PASSWORD" android:gravity="center" android:background="#22000000" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="PASWORD"/></LinearLayout>
定義好每一行的View樣式後我們回到getView()中方法中
public View getView(int position, View convertView, ViewGroup parent) { View view =View.inflate(nextActivity.this, R.layout.list_resoure, null);//R.layout.list_resoure為剛剛定義好的樣式 TextView tv_id = (TextView) view.findViewById(R.id.ID); TextView tv_name = (TextView) view.findViewById(R.id.NAME); TextView tv_psd = (TextView) view.findViewById(R.id.PASSWORD);//擷取到list_resoure中的控制項 tv_id.setText(userInfo.get(position).getId()); tv_name.setText(userInfo.get(position).getName()); tv_psd.setText(userInfo.get(position).getPassword());//為list_resoure中的控制項賦值,userInfo為所有要顯示的資料的List泛型 return view;//返回這一行資料顯示在螢幕上}
不要忘記在getCount()方法中返回資料的總行數
@Overridepublic int getCount() { return userInfo.size();//傳回值為int類型,表示資料的總行數}
getItem()和getItemId()方法可無視。
最後,使用ListView的setAdapter來綁定我們定義好的資料配接器Myadpter了
ListView lv = (ListView) findViewById(R.id.listview);lv.setAdapter(new Myadapter());
關於Android的ListView一點使用方法