1. 程式人生 > 實用技巧 >Android列表展示和手指滑動分頁

Android列表展示和手指滑動分頁

如圖所示效果,列表+手勢分頁

java程式碼:

  1. privatefinalstaticStringTAG=AlarmCenterActivity.class.getName();
  2. privateScrollLayoutmScrollLayout;
  3. privateList<SpinnerItem>agentList=newArrayList<SpinnerItem>();
  4. privateSpinnersp_agent;//主機下拉框
  5. privateEditTextealarm_name;//例項名稱
  6. privateButtonserach_btn;//搜尋按鈕
  7. privateScrollPageControlViewpageControl;
  8. publicMyHandlermyHandler;
  9. privateDataLoadingdataLoad;
  10. List<Map>list=newArrayList<Map>();//web端獲取的資料
  11. //存放下拉選中的值
  12. StringtmpAgent="";//主機
  13. //告警中心列表
  14. finalStringALARM_URL="xxxxxx";
  15. //主機下拉
  16. finalStringAGENT_URL="xxxxxxxxxx";
  17. //查詢條件--主機名稱
  18. Strings_agent_name="";
  19. //查詢條件--例項名稱
  20. Strings_alarm_name=""
    ;
  21. @Override
  22. protectedvoidonCreate(BundlesavedInstanceState){
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_alarmcenter);
  25. initUI();
  26. Toast.makeText(AlarmCenterActivity.this,"正在載入資料...",Toast.LENGTH_SHORT).show();
  27. //起一個執行緒更新資料
  28. MyThreadm=newMyThread();
  29. newThread(m).start();
  30. }
  31. // 獲取元件初始化值
  32. privatevoidinitUI(){
  33. dataLoad=newDataLoading();
  34. mScrollLayout=(ScrollLayout)findViewById(R.id.ScrollLayoutTest);
  35. myHandler=newMyHandler(this,1);
  36. sp_agent=(Spinner)findViewById(R.id.sp_agent);
  37. ealarm_name=(EditText)findViewById(R.id.Ealarm_name);
  38. serach_btn=(Button)findViewById(R.id.search);
  39. //主機下拉資料來源
  40. List<NameValuePair>params=newArrayList<NameValuePair>();
  41. params.add(newBasicNameValuePair("id","agent_id"));
  42. params.add(newBasicNameValuePair("name","agent_name"));
  43. try{
  44. StringstrAgents=HttpIface.doPost(AGENT_URL,params);
  45. JSONObjectjson=newJSONObject(strAgents);
  46. Iterator<String>it=json.keys();
  47. SpinnerItemspinnerItem;
  48. Stringkey;
  49. //預設全部
  50. SpinnerItemadd_spinnerItem=newSpinnerItem("","全部");
  51. agentList.add(add_spinnerItem);
  52. while(it.hasNext()){
  53. key=it.next();
  54. spinnerItem=newSpinnerItem(key,(String)json.get(key));
  55. agentList.add(spinnerItem);
  56. }
  57. }catch(JSONExceptione){
  58. Log.e(TAG,"jsonconverterror!");
  59. e.printStackTrace();
  60. }catch(ClientProtocolExceptione){
  61. Log.e(TAG,"HttpIface.doPostClientProtocolException");
  62. e.printStackTrace();
  63. }catch(IOExceptione){
  64. Stringmessage="";
  65. if(message.indexOf("Theoperationtimedout")>-1){
  66. message="呼叫服務超時!";
  67. }else{
  68. message="呼叫服務出現網路異常!";
  69. }
  70. DialogUtil.displayError(AlarmCenterActivity.this,message,newOnClickListener(){
  71. @Override
  72. publicvoidonClick(Viewv){
  73. }
  74. });
  75. Log.e(TAG,"呼叫服務超時或出現網路異常:"+ExceptionHandler.getErrorMessage(e));
  76. }
  77. /**
  78. *下拉框處理
  79. */
  80. //將可選內容與ArrayAdapter連線
  81. ArrayAdapters_agent_adapter=newArrayAdapter(this,android.R.layout.simple_spinner_item,agentList);
  82. //設定下拉列表的風格
  83. s_agent_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  84. //將s_agent_adapter新增到sp_agent中
  85. sp_agent.setAdapter(s_agent_adapter);
  86. //新增主機下拉框Spinner事件監聽
  87. sp_agent.setOnItemSelectedListener(newSpinner.OnItemSelectedListener(){
  88. @Override
  89. publicvoidonItemSelected(AdapterView<?>arg0,Viewarg1,
  90. intarg2,longarg3){
  91. tmpAgent=agentList.get(arg2).getKey();
  92. //設定顯示當前選擇的項
  93. arg0.setVisibility(View.VISIBLE);
  94. }
  95. @Override
  96. publicvoidonNothingSelected(AdapterView<?>arg0){
  97. arg0.setVisibility(View.VISIBLE);
  98. }
  99. });
  100. //查詢按鈕的事件監聽
  101. serach_btn.setOnClickListener(newButton.OnClickListener(){
  102. publicvoidonClick(Viewv){
  103. s_alarm_name=ealarm_name.getText().toString();
  104. s_agent_name=tmpAgent;
  105. mScrollLayout.removeAllViews();
  106. //重新載入
  107. list.clear();
  108. getListData();
  109. inttotalPages=0;
  110. if((list.size()%AlarmCenterAdapter.APP_PAGE_SIZE)==0){
  111. totalPages=list.size()/AlarmCenterAdapter.APP_PAGE_SIZE;
  112. }else{
  113. totalPages=list.size()/AlarmCenterAdapter.APP_PAGE_SIZE+1;
  114. }
  115. for(inti=0;i<totalPages;i++){
  116. ListViewappPage=newListView(AlarmCenterActivity.this);
  117. appPage.setAdapter(newAlarmCenterAdapter(AlarmCenterActivity.this,list,i));
  118. appPage.setOnItemClickListener(listener);
  119. mScrollLayout.addView(appPage);
  120. }
  121. //載入分頁
  122. pageControl=(ScrollPageControlView)findViewById(R.id.pageControl);
  123. pageControl.bindScrollViewGroup(mScrollLayout);
  124. //載入分頁資料
  125. dataLoad.bindScrollViewGroup(mScrollLayout);
  126. mScrollLayout.snapToScreen(0);
  127. }
  128. });
  129. }
  130. //更新後臺資料
  131. classMyThreadimplementsRunnable{
  132. publicvoidrun(){
  133. Messagemsg=myHandler.obtainMessage();
  134. Bundlebundle=newBundle();//存放資料
  135. getListData();
  136. JSONArrayja=newJSONArray(list);
  137. bundle.putString("alarmList",ja.toString());
  138. msg.setData(bundle);
  139. AlarmCenterActivity.this.myHandler.sendMessage(msg);//向Handler傳送訊息,更新UI
  140. }
  141. }
  142. //獲取資料
  143. classMyHandlerextendsHandler{
  144. privateAlarmCenterActivitymContext;
  145. publicMyHandler(Contextconn,inta){
  146. mContext=(AlarmCenterActivity)conn;
  147. }
  148. //子類必須重寫此方法,接收資料
  149. @Override
  150. publicvoidhandleMessage(Messagemsg){
  151. super.handleMessage(msg);
  152. Bundlebundle=msg.getData();
  153. StringalarmList=bundle.getString("alarmList");
  154. if(null!=alarmList){
  155. inttotalPages=0;
  156. if((list.size()%AlarmCenterAdapter.APP_PAGE_SIZE)==0){
  157. totalPages=list.size()/AlarmCenterAdapter.APP_PAGE_SIZE;
  158. }else{
  159. totalPages=list.size()/AlarmCenterAdapter.APP_PAGE_SIZE+1;
  160. }
  161. for(inti=0;i<totalPages;i++){
  162. ListViewappPage=newListView(mContext);
  163. appPage.setAdapter(newAlarmCenterAdapter(mContext,list,i));
  164. appPage.setOnItemClickListener(listener);
  165. mScrollLayout.addView(appPage);
  166. }
  167. //載入分頁
  168. pageControl=(ScrollPageControlView)findViewById(R.id.pageControl);
  169. pageControl.bindScrollViewGroup(mScrollLayout);
  170. //載入分頁資料
  171. dataLoad.bindScrollViewGroup(mScrollLayout);
  172. }
  173. }
  174. }
  175. //從伺服器獲取資料並轉換
  176. publicvoidgetListData(){
  177. Map<String,String>map=null;
  178. StringstrResult=HttpIface.doGet(ALARM_URL);
  179. if(!"".equals(strResult)&&null!=strResult){
  180. JSONTokenerjsonParser=newJSONTokener(strResult);
  181. JSONObjectjsonObject;
  182. try{
  183. jsonObject=(JSONObject)jsonParser.nextValue();
  184. Stringprgjson=jsonObject.getString("alarmCur");
  185. JSONArrayjsonArray=newJSONArray(prgjson);
  186. for(inti=0;i<jsonArray.length();i++){//
  187. JSONObjectitem=jsonArray.getJSONObject(i);//每條記錄又由幾個Object物件組成
  188. Stringkpi_instance_id=item.getString("KPI_INSTANCE_ID");//獲取物件對應的值
  189. Stringagent_name=item.getString("AGENT_NAME");//主機
  190. 。。。。。。
  191. //查詢條件全部不為空
  192. if(!s_agent_name.equals("")&&!s_alarm_name.equals("")){
  193. if(agent_name.equals(s_agent_name)&&kpi_instance_name.trim().indexOf(s_alarm_name)!=-1){
  194. map=newHashMap<String,String>();//存放到MAP裡面
  195. map.put("kpi_instance_id",kpi_instance_id);
  196. map.put("agent_name",agent_name);
  197. 。。。。。。
  198. list.add(map);
  199. }
  200. }
  201. //按程式名稱查詢
  202. if(s_agent_name.equals("")&&!s_alarm_name.equals("")){
  203. if(kpi_instance_name.trim().indexOf(s_alarm_name)!=-1){
  204. map=newHashMap<String,String>();//存放到MAP裡面
  205. map.put("kpi_instance_id",kpi_instance_id);
  206. map.put("agent_name",agent_name);
  207. 。。。。。。
  208. list.add(map);
  209. }
  210. }
  211. //按主機名稱模糊查詢
  212. if(!s_agent_name.equals("")&&s_alarm_name.equals("")){
  213. if(agent_name.equals(s_agent_name)){
  214. map=newHashMap<String,String>();//存放到MAP裡面
  215. map.put("kpi_instance_id",kpi_instance_id);
  216. map.put("agent_name",agent_name);
  217. 。。。。。。
  218. list.add(map);
  219. }
  220. }
  221. //查詢全部
  222. if(s_agent_name.equals("")&&s_alarm_name.equals("")){
  223. map=newHashMap<String,String>();//存放到MAP裡面
  224. map.put("kpi_instance_id",kpi_instance_id);
  225. map.put("agent_name",agent_name);
  226. 。。。。。。。
  227. map.put("user_id_c",user_id_c);
  228. list.add(map);
  229. }
  230. }
  231. }catch(JSONExceptione){
  232. e.printStackTrace();
  233. }
  234. }
  235. }
  236. //分頁資料
  237. classDataLoading{
  238. privateintcount;
  239. publicvoidbindScrollViewGroup(ScrollLayoutscrollViewGroup){
  240. this.count=scrollViewGroup.getChildCount();
  241. scrollViewGroup.setOnScreenChangeListenerDataLoad(newOnScreenChangeListenerDataLoad(){
  242. publicvoidonScreenChange(intcurrentIndex){
  243. Log.i(TAG,"onScreenChange頁碼="+currentIndex);
  244. generatePageControl(currentIndex);
  245. }
  246. });
  247. }
  248. privatevoidgeneratePageControl(intcurrentIndex){
  249. if(count==currentIndex+1){
  250. }
  251. }
  252. }

//列表展示給各列賦值

  1. //獲取元件賦值
  2. publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
  3. //TODOAuto-generatedmethodstub
  4. MapappInfo=mList.get(position);
  5. AppItemappItem;
  6. if(convertView==null){
  7. Viewv=LayoutInflater.from(mContext).inflate(R.layout.item_alarmcenter,null);
  8. appItem=newAppItem();
  9. appItem.num=(TextView)v.findViewById(R.id.num);
  10. appItem.agent_name=(TextView)v.findViewById(R.id.agent_name);
  11. 。。。。。。。。
  12. v.setTag(appItem);
  13. convertView=v;
  14. }else{
  15. appItem=(AppItem)convertView.getTag();
  16. }
  17. //賦值
  18. appItem.num.setText(position+1+"");
  19. appItem.agent_name.setText(appInfo.get("agent_name")==null?"":appInfo.get("agent_name").toString());
  20. appItem.coll_value.setText(appInfo.get("coll_value")==null?"":appInfo.get("coll_value").toString());
  21. appItem.kpi_instance_name.setText(appInfo.get("kpi_instance_name")==null?"":appInfo.get("kpi_instance_name").toString());
  22. 。。。。。
  23. returnconvertView;
  24. }

查詢元件和列表表頭的XML list_alarmcenter.xml

  1. <!--查詢條件-->
  2. <LinearLayout
  3. android:layout_width="fill_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="horizontal">
  6. <LinearLayout
  7. android:layout_width="0dip"
  8. android:layout_height="wrap_content"
  9. android:layout_weight="9"
  10. android:background="@drawable/sys_btn_query_pressed"
  11. android:gravity="center_vertical|left"
  12. android:orientation="horizontal">
  13. <TextView
  14. android:id="@+id/txtagent"
  15. style="@style/label_text"
  16. android:layout_width="0dip"
  17. android:layout_weight="1"
  18. android:text="主機:"/>
  19. <Spinner
  20. android:id="@+id/sp_agent"
  21. style="@style/edit_text"
  22. android:layout_width="0dip"
  23. android:layout_height="wrap_content"
  24. android:layout_weight="2"
  25. android:gravity="left"/>
  26. </LinearLayout>
  27. <Button
  28. android:id="@+id/search"
  29. style="@style/button"
  30. android:layout_width="0dip"
  31. android:layout_marginLeft="20dip"
  32. android:layout_weight="1"/>
  33. </LinearLayout>
  34. <LinearLayout
  35. android:layout_width="fill_parent"
  36. android:layout_height="wrap_content"
  37. android:layout_marginTop="5dip"
  38. android:orientation="vertical">
  39. <!--標題-->
  40. <LinearLayout
  41. android:layout_width="fill_parent"
  42. android:layout_height="fill_parent"
  43. android:background="@drawable/page_title_bg">
  44. <Viewstyle="@style/vertical_layout"/>
  45. <TextView
  46. android:id="@+id/alarm_num"
  47. android:layout_width="70dp"
  48. android:layout_height="wrap_content"
  49. android:gravity="center_vertical|center_horizontal"
  50. android:padding="10dp"
  51. android:singleLine="true"
  52. android:text="序號"
  53. android:textColor="#000000"
  54. android:textSize="16dp"
  55. android:textStyle="bold"/>
  56. <Viewstyle="@style/vertical_layout"/>
  57. <TextView
  58. android:id="@+id/textView1"
  59. android:layout_width="160dp"
  60. android:layout_height="wrap_content"
  61. android:gravity="center_vertical|center_horizontal"
  62. android:padding="10dp"
  63. android:singleLine="true"
  64. android:text="主機"
  65. android:textColor="#000000"
  66. android:textSize="16dp"
  67. android:textStyle="bold"/>
  68. <Viewstyle="@style/vertical_layout"/>
  69. 。。。。。。。。
  70. </LinearLayout>

// 給列表賦值元件 item_alarmcenter.xml

  1. <LinearLayout
  2. android:id="@+id/view"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="horizontal">
  6. <Viewstyle="@style/vertical_layout"/>
  7. <!--序號-->
  8. <TextView
  9. android:id="@+id/num"
  10. android:layout_width="70dp"
  11. android:layout_height="wrap_content"
  12. android:gravity="center_vertical|center_horizontal"
  13. android:padding="10dp"
  14. android:singleLine="true"
  15. android:textColor="#000000"
  16. android:textSize="16dp"/>
  17. <Viewstyle="@style/vertical_layout"/>
  18. <!--主機-->
  19. <TextView
  20. android:id="@+id/agent_name"
  21. android:layout_width="160dp"
  22. android:layout_height="wrap_content"
  23. android:gravity="center_vertical|center_horizontal"
  24. android:padding="10dp"
  25. android:singleLine="true"
  26. android:textColor="#000000"
  27. android:textSize="16dp"/>
  28. <Viewstyle="@style/vertical_layout"/>
  29. 。。。。。。。。
  30. </LinearLayout>

//滑動元件ScrollLayout scroll_page_main.xml

  1. <RelativeLayout
  2. android:id="@+id/myView"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <com.sunrise.common.component.ScrollLayout
  6. xmlns:android="http://schemas.android.com/apk/res/android"
  7. android:id="@+id/ScrollLayoutTest"
  8. android:layout_width="fill_parent"
  9. android:layout_height="fill_parent"/>
  10. <com.sunrise.common.component.ScrollPageControlView
  11. android:id="@+id/pageControl"
  12. android:layout_width="fill_parent"
  13. android:layout_height="40px"
  14. android:layout_alignParentBottom="true"
  15. android:gravity="center"/>
  16. </RelativeLayout>

以上倆個xml 檔案 分別引入到總的 xml 檔案中。

  1. <includelayout="@layout/list_alarmcenter"/>
  2. <includelayout="@layout/scroll_page_main"/>

列表展示詳解:

listView開始繪製的時候,首先呼叫getCount()函式,根據他的返回值得到listView的長度,然後根據這個長度,呼叫getView()逐一繪製每一行。如果你的getCount()返回值是0的話,列表將不顯示同樣return 1,就只顯示一行。

getView()有三個引數,position表示將顯示的是第幾行,covertView是從佈局檔案中inflate來的佈局。我們用LayoutInflater的方法將定義好的 item_alarmcenter.xml檔案提取成View例項用來顯示。然後將xml檔案中的各個元件例項化(簡單的findViewById()方法)。這樣便可以將資料對應到各個元件上了。至此一個自定義的listView就完成了,現在讓我們回過頭從新審視這個過程。系統要繪製ListView了,他首先獲得要繪製的這個列表的長度,然後開始繪製第一行,怎麼繪製呢?呼叫getView()函式。在這個函式裡面首先獲得一個View(實際上是一個ViewGroup),然後再例項並設定各個元件,顯示之。好了,繪製完這一行了。那 再繪製下一行,直到繪完為止。

手勢滑動:

1. 該類和LinearLayoutRelativeLayout等佈局都是ViewGroup的子類。LinearLayout可以在屬性中指定view的排列方式——橫向或縱向,而我們自己寫的這個類是通過onLayout(boolean changed, int l, int t, int r, int b)方法來自行指定排列方向的。我們這裡指定的是橫向。

2. 該類中用到了一些我們不常用的類,如VelocityTracker和Scroller,大家可以參考Android開發文件研究一下。

轉載於:https://blog.51cto.com/hanyijun85/1175627